Join、CountDownLatch、cyclicBarrier、semaphore的用法与区别

Join

Thread t1 = new Thread(new run());

Thread t2 = new Thread(new run());

Thread t3 = new Thread(new run());

t1.join();

t2.join();

t3.join();

System.out.println("all former thread is dead!!!!!")

1.调用join()方法会阻塞当前线程,直到被调用线程死亡

2.必须能获取到被调用线程的对象锁

CountDownLatch

CountDownLatch count = new CountDownLatch(2)

new Thread(new runable(){

//do somethine

 count.countDown();

//go on do somethine

}).start();

//thread2.start()

count.await();

//go on do something

1. await()方法阻塞当前线程

2.在子线程里调用 countDown()方法,并不会阻塞子线程,子线程也还是活的


cyclicBarrier

 CyclicBarrier barrier  = new CyclicBarrier(N);

new thread(new runable(){

//do somethine

barrier.await();

//do something

}).start()

1.在子线程中调用wait()方法,阻塞子线程

2.在所有线程到达wait()方法后,才一起执行后面的自己的逻辑

3.可以在构造函数中设置回调方法,在wait唤醒后执行回调逻辑

semaphore

Semaphore semaphore = new semaphore(number);

new Thread(new runable(){

                semaphore.acquire();

                System.out.println("get success");

                Thread.sleep(2000);

                System.out.println("finished my job ");

                semaphore.release()

})

在同一线程中调用 semaphore.acquire(),如果获取成功执行代码,否则阻塞,执行完后再release,通知其它竞争者

你可能感兴趣的:(Join、CountDownLatch、cyclicBarrier、semaphore的用法与区别)