62,614
社区成员
发帖
与我相关
我的任务
分享
public synchronized void set(String name)
{
while (flag)//当flag为true时,假设t1进入此方法
{
try
{
wait();//让t1进入res的等待队列,t1阻塞中。。。
} catch (Exception e)
{
}
//到这一步,t1被其他消费者线程唤醒,执行一下代码(flag已经被消费者线程设为false了)
this.name = name + "......" + bianhao++;
System.out.println(Thread.currentThread().getName() + "......"
+ this.name);
flag = true; //flag再次被设为true
this.notifyAll();//唤醒其它线程,再次进入while循环,t1就出不了这个while循环
}
}
因此,你应该将set()和out()方法中while改为if,以下代码仅供参考,以set()方法为例:
public synchronized void set(String name)
{
if (flag)
{
try
{
wait();
} catch (Exception e)
{
}
}
this.name = name + "......" + bianhao++;
System.out.println(Thread.currentThread().getName() + "......"
+ this.name);
flag = true;
this.notifyAll();
}
2、如上,将Res类中set()和out()方法中的while改为if之后,你的程序就能跑起来啦
class Res {
private boolean flag = false;
private String name;
private int bianhao = 1;
public synchronized void set(String name) {
while (flag) {
try {
wait();
} catch (Exception e) {
}
this.name = name + "......" + bianhao++;
System.out.println(Thread.currentThread().getName() + "......"
+ this.name);
flag = true;
this.notifyAll();
}
}
public synchronized void out() {
while (!flag) {
try {
wait();
} catch (Exception e) {
}
System.out.println("consume:" + name + "........." + bianhao++);
flag = false;
this.notifyAll();
}
}
}
class Produce implements Runnable {
Res r;
Produce(Res r) {
this.r = r;
}
public void run() {
while (true)
r.set("商品");
}
}
class Sale implements Runnable {
Res r;
Sale(Res r) {
this.r = r;
}
public void run() {
while (true)
r.out();
}
}
class lx {
public static void main(String[] args) {
Res r = new Res();
Produce pr = new Produce(r);
Sale sal = new Sale(r);
Thread t1 = new Thread(pr);
Thread t2 = new Thread(pr);
Thread t3 = new Thread(sal);
Thread t4 = new Thread(sal);
t1.start();
t2.start();
t3.start();
t4.start();
}
}