JUC梳理

JUC包的分类

JUC梳理_第1张图片
JUC梳理_第2张图片

并发工具类

JUC梳理_第3张图片

CountDownLatch

JUC梳理_第4张图片

Demo

public class CountDownLatchDemo {
     
    public static void main(String[] args) throws InterruptedException {
     
        new CountDownLatchDemo().go();
    }
    private void go() throws InterruptedException {
     
        CountDownLatch countDownLatch = new CountDownLatch(3);
        new Thread(new Task(countDownLatch),"Thread1").start();
        Thread.sleep(1000);
        new Thread(new Task(countDownLatch),"Thread2").start();
        Thread.sleep(1000);
        new Thread(new Task(countDownLatch),"Thread3").start();
        countDownLatch.await();
        System.out.println("所有线程已到达,主线程开始执行"+System.currentTimeMillis());
    }

    class Task implements Runnable {
     
        private CountDownLatch countDownLatch;

        public Task(CountDownLatch countDownLatch) {
     
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
     
            System.out.println("线程"+Thread.currentThread().getName() + "已经到达"+System.currentTimeMillis());
            countDownLatch.countDown();
        }
    }
}

运行结果

线程Thread1已经到达1599366228071
线程Thread2已经到达1599366229085
线程Thread3已经到达1599366230100
所有线程已到达,主线程开始执行1599366230101

CyclicBarrier

JUC梳理_第5张图片
CyclicBarrier和CountDownLatch不同的地方在于,CountDownLatch的子线程可以在其他线程等待的状态下继续执行,而CyclicBarrier要等到所有线程都awaiting再一起执行。

Demo

public class CyclicBarrierDemo {
     
    public static void main(String[] args) throws InterruptedException {
     
        new CyclicBarrierDemo().go();
    }
    private void go() throws InterruptedException {
     
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        new Thread(new Task(cyclicBarrier),"Thread1").start();
        Thread.sleep(1000);
        new Thread(new Task(cyclicBarrier),"Thread2").start();
        Thread.sleep(1000);
        new Thread(new Task(cyclicBarrier),"Thread3").start();
    }

    class Task implements Runnable {
     
        private CyclicBarrier cyclicBarrier;

        public Task(CyclicBarrier cyclicBarrier) {
     
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
     
            System.out.println("线程"+Thread.currentThread().getName() + "已经到达"+System.currentTimeMillis());
            try {
     
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
     
                e.printStackTrace();
            }
            System.out.println("线程"+Thread.currentThread().getName() + "开始处理"+System.currentTimeMillis());
        }
    }
}

运行结果

线程Thread1已经到达1599367002749
线程Thread2已经到达1599367003757
线程Thread3已经到达1599367004769
线程Thread1开始处理1599367004770
线程Thread2开始处理1599367004771
线程Thread3开始处理1599367004771

Semaphore

JUC梳理_第6张图片

Demo

public class SemaphoreDemo {
     
    public static void main(String[] args) {
     
        ThreadFactory threadFactory = new NameTreadFactory();
        RejectedExecutionHandler handler = new MyIgnorePolicy();
        // 线程池
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 50, 10,
                TimeUnit.SECONDS, workQueue, threadFactory, handler);
        // 只能5个线程同时访问
        final Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 20; i++) {
     
            final int NO = i;
            Runnable run = new Runnable() {
     
                @Override
                public void run() {
     
                    try {
     
                        // 获取许可
                        semaphore.acquire();
                        System.out.println("Accessing: " + NO);
                        Thread.sleep((long) (Math.random() * 10000));
                        // 访问完后,释放
                        semaphore.release();
                    } catch (InterruptedException e) {
     
                        e.printStackTrace();
                    }

                }
            };
            poolExecutor.execute(run);
        }
        // 退出线程池
        poolExecutor.shutdown();
    }

    static class NameTreadFactory implements ThreadFactory {
     

        private final AtomicInteger mThreadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
     
            Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement());
            System.out.println(t.getName() + " has been created");
            return t;
        }
    }

    public static class MyIgnorePolicy implements RejectedExecutionHandler {
     

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
     
            doLog(r, e);
        }

        private void doLog(Runnable r, ThreadPoolExecutor e) {
     
            // 可做日志记录等
            System.err.println(r.toString() + " rejected");
//          System.out.println("completedTaskCount: " + e.getCompletedTaskCount());
        }
    }
}

运行结果

my-thread-0 has been created
my-thread-1 has been created
my-thread-2 has been created
my-thread-3 has been created
my-thread-4 has been created
my-thread-5 has been created
my-thread-6 has been created
my-thread-7 has been created
my-thread-8 has been created
my-thread-9 has been created
my-thread-10 has been created
my-thread-11 has been created
my-thread-12 has been created
my-thread-13 has been created
my-thread-14 has been created
my-thread-15 has been created
my-thread-16 has been created
my-thread-17 has been created
Accessing: 0
Accessing: 1
Accessing: 4
Accessing: 5
Accessing: 6
Accessing: 7
Accessing: 3
Accessing: 8
Accessing: 9
Accessing: 10
Accessing: 11
Accessing: 12
Accessing: 13
Accessing: 14
Accessing: 15
Accessing: 16
Accessing: 17
Accessing: 18
Accessing: 19
Accessing: 2

Exchanger

JUC梳理_第7张图片

Demo

public class ExchangerDemo {
     
    public static void main(String[] args) {
     
        Exchanger<String> exchanger = new Exchanger<>();
        ThreadFactory threadFactory = new NameTreadFactory();
        RejectedExecutionHandler handler = new MyIgnorePolicy();
        // 线程池
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 2, 10,
                TimeUnit.SECONDS, workQueue, threadFactory, handler);
        poolExecutor.execute(() ->{
     
            try {
     
                // 女生对男生说的话
                String girl = exchanger.exchange("我其实暗恋你很久了......");
                System.out.println("女生说: "+girl);
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
        });
        poolExecutor.execute(() ->{
     
            try {
     
                System.out.println("女生慢慢从教室走出来.......");
                TimeUnit.SECONDS.sleep(3);
                // 男生对女生说的话
                String boy = exchanger.exchange("我很喜欢你......");
                System.out.println("男生说: "+boy);
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
        });
    }
    static class NameTreadFactory implements ThreadFactory {
     

        private final AtomicInteger mThreadNum = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
     
            Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement());
            System.out.println(t.getName() + " has been created");
            return t;
        }
    }

    public static class MyIgnorePolicy implements RejectedExecutionHandler {
     

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
     
            doLog(r, e);
        }

        private void doLog(Runnable r, ThreadPoolExecutor e) {
     
            // 可做日志记录等
            System.err.println(r.toString() + " rejected");
//          System.out.println("completedTaskCount: " + e.getCompletedTaskCount());
        }
    }
}

运行结果

my-thread-0 has been created
my-thread-1 has been created
女生慢慢从教室走出来.......
男生说: 我其实暗恋你很久了......
女生说: 我很喜欢你......

BlockingQueue

JUC梳理_第8张图片
JUC梳理_第9张图片
JUC梳理_第10张图片

你可能感兴趣的:(Java,thread,多线程,java)