62,621
社区成员
发帖
与我相关
我的任务
分享
package jack;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
public class Test {
public static void main(String[] args) throws Exception {
BlockingQueue<Integer> bq = new LinkedBlockingDeque<Integer>();
Producer p = new Producer(bq);
Consumer c = new Consumer(bq);
new Thread(p).start();
new Thread(c).start();
}
}
class Producer implements Runnable {
BlockingQueue<Integer> bq;
public Producer(BlockingQueue<Integer> bq) {
this.bq = bq;
}
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while (true) {
try {
bq.put(++i);
System.out.println("produce ");
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
BlockingQueue<Integer> bq;
public Consumer(BlockingQueue<Integer> bq) {
this.bq = bq;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
bq.take();
System.out.println("consume ");
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}