50,549
社区成员
发帖
与我相关
我的任务
分享
public class Test {
public static void main(String[] args) {
Queue<Integer> store = new ArrayBlockingQueue<Integer>(10);
new Creator(store,10,"Creator1").start();
new Creator(store,10,"Creator2").start();
new Consumer(store,"Consumer1").start();
new Consumer(store,"Consumer2").start();
new Consumer(store,"Consumer3").start();
}
}
class Creator extends Thread{
private Queue<Integer> store;
private int sotreSize;
public Creator(Queue<Integer> store,int sotreSize,String name) {
super(name);
this.store = store;
this.sotreSize = sotreSize;
}
@Override
public void run() {
while(true){
try {
synchronized (store) {
if(store.size()==sotreSize){
System.out.println("仓库已满,等待消费...");
store.wait();
}
int e = (int) (Math.random()*10);
store.add(e);
System.out.println(Thread.currentThread().getName()+":"+e+"入库");
store.notify();
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
class Consumer extends Thread{
private Queue<Integer> store;
public Consumer(Queue<Integer> store,String name) {
super(name);
this.store = store;
}
@Override
public void run() {
while(true){
try {
synchronized (store) {
if(store.isEmpty()){
System.out.println("仓库为空,等待生产...");
store.wait();
}else{
Integer e = store.poll();
System.out.println(Thread.currentThread().getName()+":"+e+"出库");
}
store.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
synchronized (store) {
if(store.size()==sotreSize){
System.out.println("仓库已满,等待消费...");
store.wait();
}else{
int e = (int) (Math.random()*10);
store.add(e);
System.out.println(Thread.currentThread().getName()+":"+e+"入库");
}
store.notify();
}
来讨论一下问题2.