- public class ProduceConsumerDemo3 {
- public static void main(String[] args) {
- //创建一个容量为1的队列
- BlockingQueue<String> bq=new ArrayBlockingQueue<String>(1);
- //启动三个生产者
- new Thread(new Producer1(bq)).start();
- new Thread(new Producer1(bq)).start();
- new Thread(new Producer1(bq)).start();
-
- //启动一个消费者
- new Thread(new Consumer1(bq)).start();
- }
- }
- class Producer1 implements Runnable
- {
- private BlockingQueue<String> bq;
- public Producer1(BlockingQueue<String> bq)
- {
- this.bq=bq;
- }
- @Override
- public void run() {
- String []strArr=new String[]{"java","struts","Spring"};
- for (int i = 0; i < 99999; i++)
- {
- System.out.println(Thread.currentThread().getName()+"----生产者----");
- try {
- bq.put(strArr[i%3]);
- } catch (Exception e) {
- // TODO: handle exception
- }
- }
- }
- }
- class Consumer1 implements Runnable
- {
- private BlockingQueue<String> bq;
- public Consumer1(BlockingQueue<String> bd)
- {
- this.bq=bq;
- }
- @Override
- public void run() {
- while (true) {
-
- try {
- System.out.println(Thread.currentThread().getName()+"---消费者--"+bq.take());
- } catch (Exception e) {
- // TODO: handle exception
- }
-
- }
- }
复制代码 |
|