厨师和服务生的问题~设计一个无限的循环,可为什么总是只执行一次呢?~...求教!~class Cai
{
boolean falg = false;
int i = 0;
}
class ChuShi implements Runnable
{
Cai b;
ChuShi(Cai b)
{
this.b = b;
}
public synchronized void doCai()
{
if(b.falg)
try{b.wait();}catch(Exception e){}
b.i++;
System.out.println("厨师已经做好了第 "+b.i+" 道菜...呼唤使者...");
b.falg = false;
b.notify();
}
public void run()
{
while(true)
{
doCai();
}
}
}
class FuWuSheng implements Runnable
{
Cai b;
FuWuSheng(Cai b)
{
this.b = b;
}
public synchronized void get()
{
if(!b.falg)
try{b.wait();}catch(Exception e){}
System.out.println("服务生拿走了第 "+b.i+" 道菜...");
b.falg = true;
b.notify();
}
public void run()
{
while(true)
{
get();
}
}
}
class Demo
{
public static void main(String agrs[])
{
Cai b = new Cai();
new Thread(new ChuShi(b)).start();
new Thread(new FuWuSheng(b)).start();
}
}
{
boolean falg = false;
int i = 0;
}
class ChuShi implements Runnable
{
Cai b;
ChuShi(Cai b)
{
this.b = b;
}
public synchronized void doCai()
{
if(b.falg)
try{b.wait();}catch(Exception e){}
b.i++;
System.out.println("厨师已经做好了第 "+b.i+" 道菜...呼唤使者...");
b.falg = false;
b.notify();
}
public void run()
{
while(true)
{
doCai();
}
}
}
class FuWuSheng implements Runnable
{
Cai b;
FuWuSheng(Cai b)
{
this.b = b;
}
public synchronized void get()
{
if(!b.falg)
try{b.wait();}catch(Exception e){}
System.out.println("服务生拿走了第 "+b.i+" 道菜...");
b.falg = true;
b.notify();
}
public void run()
{
while(true)
{
get();
}
}
}
class Demo
{
public static void main(String agrs[])
{
Cai b = new Cai();
new Thread(new ChuShi(b)).start();
new Thread(new FuWuSheng(b)).start();
}
}
By executing the body of a synchronized statement that synchronizes on the object.
For objects of type Class, by executing a synchronized static method of that class.lz的代码实现是又问题的,请看一下jdk里边的描述.
}
this.b = b;
} public void doCai() {
synchronized (b) {
if (!b.falg) try {
b.wait();
}
catch (Exception e) {}
b.i++;
System.out.println("厨师已经做好了第 " + b.i + " 道菜...呼唤使者...");
b.falg = false;
try {
Thread.sleep(1000l);
}
catch (InterruptedException e) {
e.printStackTrace();
}
b.notify();
}
} public void run() {
while (true) {
doCai();
}
}
}
this.b = b;
} public void get() {
synchronized(b){
if (b.falg) try {
b.wait();
}
catch (Exception e) {}
System.out.println("服务生拿走了第 " + b.i + " 道菜...");
b.falg = true;
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
b.notify();}
} public void run() {
while (true) {
get(); }
}
}