线程池处理数据

来源:互联网 发布:java工程师是青春饭吗 编辑:程序博客网 时间:2024/05/16 08:20
public class ProcessRunnable implements Runnable {//线程名private String name;//队列private BlockingQueue queue;//线程辅助,用于线程全部执行完成前,主线程等待private CountDownLatch countDownLatch;public ProcessRunnable(String name,BlockingQueue queue,CountDownLatch countDownLatch){this.name = name;this.queue = queue;this.countDownLatch = countDownLatch;}@Overridepublic void run() {Object obj;try {while(true){obj = queue.take();if(obj==Task.EXIT_SIGNAL){break;}if(obj == null){continue;}//处理obj}} catch (InterruptedException e) {e.printStackTrace();} finally {countDownLatch.countDown();}}}

public class Task {public static final Object EXIT_SIGNAL = new String("exit");public static void main(String[] args) {BlockingQueue queue = new SynchronousQueue();int threadCount = 5;CountDownLatch countDownLatch = new CountDownLatch(5);ExecutorService executorService = Executors.newFixedThreadPool(5);for(int i=0;i<threadCount;i++){executorService.execute(new ProcessRunnable("task"+i,queue,countDownLatch));}try{//在此处添加对象,线程会在队列中获取对象进行处理//可以得到多个对象进行处理queue.add(new Object());}finally {for(int i=0;i<threadCount;i++){try {//添加固定对象用于退出queue.put(EXIT_SIGNAL);} catch (InterruptedException e) {e.printStackTrace();}}try {//当线程其中一个线程终止数值-1countDownLatch.wait();} catch (InterruptedException e) {e.printStackTrace();}executorService.shutdown();}}}

0 0
原创粉丝点击