前言:在你无聊的时候,想想比你优秀还努力的人,也许就不觉的无聊了
今天下午没事干把买的java并发编程艺术这本书拿出来看了看,看了下也记不住,还是好记性不如烂笔头,今天讲四个并发中可能会用到的工具类,分别是:
CountDownLatch
CyclicBarrier
Semaphore
Exchanger
CountDownLatch
countDownLatch允许一个或多个线程等待其他线程完成操作.比如说有三个线程分别是老二,老大,老爸,这三个线程必须是老二吃好了,老大吃,老大吃完了,老爸吃,在钱,农村家里穷,一般有好吃的都是先留个最小的,然后才给其他兄弟姐妹吃,都不吃了,才由我们的父母吃,所以父母都不容易了,为了儿女,虽然是多个线程但是确实线性的,
我同事面试别人就问过好几次这个问题,在java或者android中常用的有2个方式实现
第一种方式:
使用jdk中Thread自带的函数join实现,join()用于当前执行线程等待join线程执行结束,其实实现原理是不停检查join线程是否存活,如果join线程存活则让当前线程永远等待,其中,wait(0)表示永远等待下去,join在jdk中的是实现方式如下:
/**
* Waits for this thread to die.
*
*
An invocation of this method behaves in exactly the same
* way as the invocation
*
*
* {@linkplain #join(long) join}{@code (0)}
*
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
*interrupted statusof the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}直到join线程中止后,线程的this.notifyAll()方法会被调用,调用notifyAll()方法是在JVM里实现的,现在把上面的例子用代码实现下:
package com.thread;
public class RunnableJob {
public static void main(String[] args) throws InterruptedException {
Worker runnableJob = new Worker();
Thread t1 = new Thread(runnableJob, "老二");
Thread t2 = new Thread(runnableJob, "老大");
Thread t3 = new Thread(runnableJob, "老爸");
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
System.out.println("主线程执行完毕----");
}
}
class Worker implements Runnable{
public void run() {
Thread thread = Thread.currentThread();
try {
Thread.sleep(5000);
System.out.println(thread.getName()+"吃完了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}log:
今天写不完,要下班,明天有时间写完