package moreCoding1;
class Person {
String name;
Person ( String name){
this. name= name;
}
}
class Shop{
private Person
p1= new Person( "服务员" ),
p2= new Person( "张三" ),
p3= new Person( "李四" );
private boolean flag= false;
Thread thread1= new Thread( new Runnable(){
public void run () {
while (true ){
while (flag == true){
try {
wait ();
} catch (Exception e ) {
}
}
synchronized ( this ) {
System . out. println( p1. name+ "上了" +">>>" +1 +"个菜" );
flag= true;
notifyAll ();
} }}}) ;
Thread thread2= new Thread( new Runnable(){
public void run () {
while (true ){
while (flag == false){
try {
wait ();
} catch (Exception e ) {
}
}
synchronized ( this ) {
System . out. println( p2. name+ "吃了" +"<<<<" +1 +"个菜" );
flag= false;
notifyAll ();
} }}}) ;
Thread thread3= new Thread( new Runnable(){
public void run () {
// TODO Auto-generated method
stub
while (true ){
while (flag == false){
try {
wait ();
} catch (Exception e ) {
}}
synchronized ( this ) {
System . out. println( p3. name+ "吃了" +"~~~~" +1 +"个菜" );
flag= false;
notifyAll ();
} }}}) ;
Shop (){
thread1. start ();
thread2. start ();
thread3. start ();
}
}
public class MyThread {
public static void main ( String[] args ) {
new Shop() ;
}
}
//
/*张三吃了<<<<1个菜
服务员上了>>>1个菜
张三吃了<<<<1个菜
服务员上了>>>1个菜
李四吃了~~~~1个菜
服务员上了>>>1个菜
李四吃了~~~~1个菜
服务员上了>>>1个菜
李四吃了~~~~1个菜*/
死锁
假如发生了这样的问题,筷子不够,筷子的跟数只有你们人数那么多,那么每个人吃饭都要先拿左手的筷子,然后再设法拿到右边的筷子,当你发现每个人左手都拿着筷子等右边的筷子的时候,死锁就产生了。