当多个生产者多个消费者时,会出现一个问题,notify时唤醒的同类的线程。解决办法:notifyAll;
public class ProducerAndConsumer {
public static void main(String[] args) {
Resource2 s = new Resource2();
Producer p = new Producer(s);
Consumer c = new Consumer(s);
Producer p1 = new Producer(s);
Consumer c1 = new Consumer(s);
new Thread(p).start();
new Thread(c).start();
new Thread(p1).start();
new Thread(c1).start();
}
}
//定义资源
class Resource2{
boolean flag =false;
int count = 0;
public synchronized void produce(){
while (!flag) {
System.out.println("producer:i hava produce" + count++);
flag = true;
this.notifyAll();
}
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void consume(){
while(flag) {
System.out.println("consumer:i have consume"+count);
flag = false;
this.notifyAll();
}
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//生产者
class Producer implements Runnable{
private Resource2 s;
Producer(Resource2 s){
this.s = s;
}
public void run(){
while (true) {
s.produce();
}
}
}
//消费者
class Consumer implements Runnable{
private Resource2 s;
Consumer(Resource2 s){
this.s = s;
}
public void run(){
while(true){
s.consume();
}
}
}
|
|