该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
不明白线程为什么卡住了? 求大神解救
代码如下
package practice;
class Resour {
private String name;
private int count = 1;
boolean flag = false;
public synchronized void set(String name) {
while (flag)
try {
this.wait();
} catch (Exception e) {
}
this.name = name + count++;
System.out.println(Thread.currentThread().getName()
+ "...producer..." + this.name);
// this.sex = sex;
flag = true;
this.notifyAll();
}
public synchronized void out() {
while (!flag)
try {
this.wait();
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName()
+ "..。。.consumer.。。.." + this.name);
flag = false;
this.notifyAll();
}
}
class Producer implements Runnable {
private Resour r;
Producer(Resour r) {
this.r = r;
} // 以便对象的唯一性
public void run() {
while (true) {
r.set("+goods+");
}
}
}
class Consumer implements Runnable {
private Resour r;
Consumer(Resour r) {
this.r = r;
} // 以便对象的唯一性
public void run() {
r.out();
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resour r = new Resour();
Producer pro = new Producer(r);
Consumer con= new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}