package com.concurrent; import java.util.concurrent.BlockingQueue; public class consumer extends Thread{ BlockingQueuessqueue; consumer(BlockingQueue bq){ this.ssqueue = bq; } @Override public void run(){ try { while(!Thread.currentThread().isInterrupted()) { Integer take = ssqueue.take(); System.out.println("我成功消费了一个"); sleep(2000); } } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.concurrent; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; public class producer extends Thread { BlockingQueuessqueue ; private int i = 0; producer(BlockingQueue bq){ this.ssqueue = bq; } @Override public void run() { while(!Thread.currentThread().isInterrupted()) { try { ssqueue.add(i++); System.out.println("我成功生产了一个"); sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.concurrent; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class test { public static void main(String[] args) { BlockingQueue bq = new ArrayBlockingQueue(5); consumer con = new consumer(bq); producer p = new producer(bq); con.start(); p.start(); } }
将在blockingqueue为满时抛出异常,但不会终止程序,只会终止producer线程,之后consumer线程继续消费,直到为0,然后阻塞队列进入阻塞状态
但是当我们使用线程池时将不会抛出异常:
package com.concurrent; import java.util.concurrent.*; public class test { public static void main(String[] args) { BlockingQueue bq = new ArrayBlockingQueue(5); consumer con = new consumer(bq); producer p = new producer(bq); ExecutorService executorService = Executors.newFixedThreadPool(20); executorService.submit(con); executorService.submit(p); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)