导航

生产者消费者synchronized wait notify

Posted on 2018-08-28 02:04  骄阳照林  阅读(159)  评论(0编辑  收藏  举报
package ProduceQueueProduce;

import java.util.Queue;

public class ProducerThread extends Thread {
public static Queue<Object> q;
private int eleNum =15;
@Override
public void run(){
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
produce();
}
}

private void produce() {
synchronized(q){
while(q.size() == eleNum){
try {
q.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
q.add(new Object());
System.out.println(Thread.currentThread().getName()+"生产者队列大小:"+ q.size());
q.notifyAll();
}
}


public ProducerThread(String name) {
super(name);
}
}
package ProduceQueueProduce;

import java.util.Queue;

public class ConsumerThread extends Thread {
public static Queue<Object> q;
@Override
public void run(){
while(true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
consume();
}
}

private void consume() {
synchronized(q){
while(q.size() == 0){
try {
q.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
q.remove();
System.out.println(Thread.currentThread().getName()+"消费者队列大小:"+q.size());
q.notifyAll();
}
}


public ConsumerThread(String name) {
super(name);
}
}

package ProduceQueueProduce;

import java.util.ArrayDeque;
import java.util.Queue;


public class Test {
public static Queue<Object> q = new ArrayDeque<>();
public static void main(String args[]) throws InterruptedException {
ConsumerThread c = new ConsumerThread("c");
ProducerThread p = new ProducerThread("p");
ProducerThread.q=q;
ConsumerThread.q = q;
p.start();
c.start();

}
}