JUC并发编程

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/takeuherat/article/details/102632087

JUC并发编程(Concurrent)

java.util.concurrent
  • CountDownLatch
public static void main(String[] args) throws InterruptedException {
        //要锁的线程数
        CountDownLatch countDownLatch = new CountDownLatch(6);
        //循环六次线程
        for (int i=0;i<6;i++){
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"同学离开教室");
                //上锁
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"班长关门");
    }
  • CyclicBarrier
CyclicBarrier cb  = new CyclicBarrier(7,()->{
            System.out.println("召唤神龙");
        });

        for (int i=1;i<=7;i++){
            final int temp = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"搜集到第"+temp+"颗龙珠");
                try {
                    cb.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
    }
  • Semaphore
Semaphore s = new Semaphore(3);//3个资源
        for (int i=1;i<=6;i++){
            new Thread(()->{
                //占用一个资源
                try {
                    s.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了车位");
                    try{
                        //暂停4秒
                        TimeUnit.SECONDS.sleep(4);
                        System.out.println(Thread.currentThread().getName()+"离开了车位");
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }finally {
                        s.release();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i));
        }
java.util.concurrent.locks
  • ReadWriteLock(读写锁)
class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    public void put(String key,Object value){
        readWriteLock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"开始写入");
            try {
                TimeUnit.MICROSECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完成");
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key){
        readWriteLock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"读取数据");
            try {
                TimeUnit.MICROSECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完成"+o);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

}
public class TestConcurrent {

    public static void main(String[] args) {
        MyCache m = new MyCache();
        for (int i = 1; i <= 7; i++) {
            final int temp = i;
            new Thread(() -> {
                m.put(temp+"",temp+"");
            }, String.valueOf(i)).start();
        }
        for (int i = 1; i <= 7; i++) {
            final int temp = i;
            new Thread(() -> {
                m.get(temp+"");
            }, String.valueOf(i)).start();
        }

    }
}
java.collections.Queue.BlockingQueue(阻塞队列)
BlockingQueue<String> b = new ArrayBlockingQueue(3);
        /*System.out.println(b.add("a"));
        System.out.println(b.add("b"));
        System.out.println(b.add("c"));

        System.out.println(b.add("d"));//添加第四个元素会报Full Queue错误
        System.out.println(b.remove());
        System.out.println(b.remove());
        System.out.println(b.remove());
        System.out.println(b.remove());//删除空队列会报noSuchElement错误*/
        /*----------------------------------------------------
        System.out.println(b.element()); //检查队首的元素

        System.out.println(b.offer("a"));//检查是否有此元素
        System.out.println(b.offer("b"));
        System.out.println(b.offer("c"));
        System.out.println(b.offer("x"));//查询不存在的值时,返回false

        System.out.println(b.poll());//移除队列中的元素
        System.out.println(b.poll());
        System.out.println(b.poll());
        System.out.println(b.poll()); //移除不存在的值返回false*/

        /*-------------------------------------------------------------
        b.put("a");
        b.put("b");
        b.put("c");
        b.put("d"); //队列已满,再添加会一直阻塞,直到有位置

        b.take();
        b.take();
        b.take();
        b.take();//队列已空,再取值会一直阻塞,直到有值可取*/

        b.offer("a",3L, TimeUnit.SECONDS); //添加如果阻塞超过3秒会退出
        b.poll(3L, TimeUnit.SECONDS); //移除如果超过3秒会退出

猜你喜欢

转载自blog.csdn.net/takeuherat/article/details/102632087