java.util.concurrent包的拆解
发布日期:2019-07-11 13:18   浏览次数:
9人阅读 2019-07-08 17:44:07

java.util.concurrent包:
1.locks局部:显式锁(互斥锁和速写锁)相关
2.atomic局部:原子变量类相关,是构建非阻塞算法的根底
3.executor局部:线程池相关
4.collection局部:并发容器相关
5.tools局部:同步工具相关,如信号量、闭锁、栅栏等功用

1.collection局部:
1.1 BlockingQueue
BlockingQueue为接口,假如要用它,需求完成它的子类:
ArrayBlockingQueue
DelayQueue
LinkedBlockingQueue
SynchronousQueue
PriorityBlockingQueue
TransferQueue

   /**
  • 在两个独立的线程中启动一个Producer和一个Consumer
  • Producer向一个共享的BlockingQueue注入字符串,而Comsumer从中拿出来
  • @Author mufeng
  • @Date 2019-7-8 11:25
    */
    public class BlockingQueueExample {
    public static void main(String[] args) {
    BlockingQueue blockingQueue=new ArrayBlockingQueue(1024);
    Producer producer=new Producer(blockingQueue);
    Consumer consumer=new Consumer(blockingQueue);
    new Thread(producer).start();
    new Thread(consumer).start();
    try {
    Thread.sleep(4000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    class Producer implements Runnable{
    private BlockingQueue blockingQueue;
    public Producer(BlockingQueue blockingQueue){this.blockingQueue=blockingQueue;
    }
    @Override
    br/>this.blockingQueue=blockingQueue;
    }
    @Override
    try {
    blockingQueue.put("1");
    Thread.sleep(1000);
    blockingQueue.put("2");
    Thread.sleep(1000);
    blockingQueue.put("3");
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    class Consumer implements Runnable{
    private BlockingQueue blockingQueue;
    public Consumer(BlockingQueue blockingQueue){
    this.blockingQueue=blockingQueue;
    }

    @Override
    public void run() {
    try {
    System.out.println(blockingQueue.take());
    System.out.println(blockingQueue.take());
    System.out.println(blockingQueue.take());
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

2.Tools局部
2.1 CountDownLatch用法

/**

  • @Author mufeng
  • @Date 2019-7-8 11:54
    */
    public class TestCountDownLatch {
    public static void main(String[] args) {
    final CountDownLatch countDownLatch=new CountDownLatch(2);
    new Thread(){
    public void run(){
    System.out.println(Thread.currentThread().getName()+"processing");
    try {
    Thread.sleep(3000);
    System.out.println(Thread.currentThread().getName()+"ended");
    countDownLatch.countDown();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }.start();
    new Thread(){
    public void run(){
    System.out.println(Thread.currentThread().getName()+"processing");
    « 上一篇:没有了
    » 下一篇:ELTRA 2NP5606 9000w
  • 友情链接:
Copyright(C) 2007-2010 EntLib.com(上海闵行区浦江镇863软件孵化基地) - 企业级的电子商务系统 基于Microsoft .Net Framework / ASP.Net / C# / AJAX 平台构建的标准电子商务系统 All Rights Reserved (R)    沪ICP备08014628号