JDK并发包零散记录

信号量

  • 它的作用是啥?

一般情况下,临界区只允许一个线程进入,而信号量呢则是同一时间允许放入多个线程

来看个demo:

package someTest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemapDemo implements Runnable{
    final Semaphore semap=new Semaphore(5);
    @Override
    public void run() {
        try {
            semap.acquire();
            //模拟耗时操作
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getId()+":done!");
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semap.release();
        }
    }
    public static void main(String[] args) {
        ExecutorService exec=Executors.newFixedThreadPool(20);
        final SemapDemo demo=new SemapDemo();
        for(int i=0;i<20;i++) {
            exec.submit(demo);
        }
    }
}

ReadWriteLock

一种读写分离锁
读——读不互斥
读——写互斥
写——写互斥

CountDownLatch

集齐七龙珠,召唤神龙的故事

来看个demo

package someTest;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo implements Runnable{
    static final CountDownLatch end=new CountDownLatch(10);
    static final CountDownLatchDemo demo=new CountDownLatchDemo();
    @Override
    public void run() {
        try {
            //模拟检查任务
            Thread.sleep(new Random().nextInt(10)*1000);
            System.out.println("check complete");
            end.countDown();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec=Executors.newFixedThreadPool(10);
        for(int i=0;i<10;i++) {
            exec.submit(demo);
        }
        //等待检查
        end.await();
        //发射火箭
        System.out.println("fire");
        exec.shutdown();
    }
}

输出结果:

check complete
check complete
check complete
check complete
check complete
check complete
check complete
check complete
check complete
check complete
fire

你可能感兴趣的:(JDK并发包零散记录)