package mashibing;
/**
* 生产者消费者
*/
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
public class ProducerAndConsumerTest {
private final static int MAX=10;
public LinkedList list=new LinkedList();
public void add() {
synchronized (list) {
while(list.size()==MAX) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(1);
System.out.println("生产者生产"+Thread.currentThread().getName()+" 现库存为:"+getCount());
list.notifyAll();
}
}
public void get() {
synchronized (list) {
while (list.size()==0) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.removeFirst();
System.out.println("消费者消费"+Thread.currentThread().getName()+" 现库存为:"+getCount());
list.notifyAll();
}
}
public synchronized int getCount() {
return list.size();
}
public static void main(String[] args) {
ProducerAndConsumerTest test=new ProducerAndConsumerTest();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
test.get();
}
}
}).start();
}
// try {
// TimeUnit.SECONDS.sleep(3);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
test.add();
}
}
}).start();
}
}
}
wait和notifyAll实现多线程的生产者和消费者
最新推荐文章于 2022-09-11 16:58:01 发布