使用重入锁未来保证消费和分发任务同步 * Created by yy on 17/2/8. */public class JavaThreadPool { public static void main(String[] args) throws InterruptedException { JavaThreadPool javaThreadPool = new JavaThreadPool(); javaThreadPool.production(); javaThreadPool.consumption(); } //设置阻塞队列容量 LinkedBlockingDeque
上面代码存在单线程执行问题:影响执行效率。
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingDeque;/** * Created by yuanyong on 17/2/8. */public class JavaThreadPool { public static void main(String[] args) throws InterruptedException { JavaThreadPool javaThreadPool = new JavaThreadPool(); javaThreadPool.production(); javaThreadPool.consumption(); } //设置阻塞队列容量 LinkedBlockingDeque linkedBlockingDeque = new LinkedBlockingDeque(100); //设置线程数量 ExecutorService pool = Executors.newFixedThreadPool(4); /** * 生产者 * * @param */ public void production() { Thread thread = new Thread(new Runnable() { @Override public void run() { int i = 0; while (true) { i++; try { linkedBlockingDeque.put(i);// System.out.println("生产了:" + i); } catch (InterruptedException e) { e.printStackTrace(); } } } }); thread.start(); } /** * 消费者 */ public void consumption() throws InterruptedException { new Thread(new Runnable() { @Override public void run() { ThreadGroup group = new ThreadGroup("测试线程组") { public void uncaughtException(Thread t, Throwable e) { System.out.println(t.getName() + ": " + e.getMessage()); } }; while (true) { pool.execute(new Examples(group, linkedBlockingDeque)); } } }).start(); }}/** * 执行线程 */class Examples extends Thread { ThreadGroup group; LinkedBlockingDeque linkedBlockingDeque; Examples(ThreadGroup group,LinkedBlockingDeque linkedBlockingDeque) { this.group = group; this.linkedBlockingDeque = linkedBlockingDeque; } @Override public void run() { try { Integer obj = (Integer) linkedBlockingDeque.take(); System.out.println("linkedBlockingDeque.size="+linkedBlockingDeque.size()); Thread.sleep(1000 * 1); System.out.println(group.getName()+":"+Thread.currentThread().getName()+": 消费了:" + obj); } catch (InterruptedException e) { e.printStackTrace(); } }}