java中的并发类_java中并发常用工具类
前言:在你無(wú)聊的時(shí)候,想想比你優(yōu)秀還努力的人,也許就不覺(jué)的無(wú)聊了
今天下午沒(méi)事干把買的java并發(fā)編程藝術(shù)這本書拿出來(lái)看了看,看了下也記不住,還是好記性不如爛筆頭,今天講四個(gè)并發(fā)中可能會(huì)用到的工具類,分別是:
CountDownLatch
CyclicBarrier
Semaphore
Exchanger
CountDownLatch
countDownLatch允許一個(gè)或多個(gè)線程等待其他線程完成操作.比如說(shuō)有三個(gè)線程分別是老二,老大,老爸,這三個(gè)線程必須是老二吃好了,老大吃,老大吃完了,老爸吃,在20年錢,農(nóng)村家里窮,一般有好吃的都是先留個(gè)最小的,然后才給其他兄弟姐妹吃,都不吃了,才由我們的父母吃,所以父母都不容易了,為了兒女,雖然是多個(gè)線程但是確實(shí)線性的,
我同事面試別人就問(wèn)過(guò)好幾次這個(gè)問(wèn)題,在java或者android中常用的有2個(gè)方式實(shí)現(xiàn)
第一種方式:
使用jdk中Thread自帶的函數(shù)join實(shí)現(xiàn),join()用于當(dāng)前執(zhí)行線程等待join線程執(zhí)行結(jié)束,其實(shí)實(shí)現(xiàn)原理是不停檢查join線程是否存活,如果join線程存活則讓當(dāng)前線程永遠(yuǎn)等待,其中,wait(0)表示永遠(yuǎn)等待下去,join在jdk中的是實(shí)現(xiàn)方式如下:
/**
* 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 status of the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}直到j(luò)oin線程中止后,線程的this.notifyAll()方法會(huì)被調(diào)用,調(diào)用notifyAll()方法是在JVM里實(shí)現(xiàn)的,現(xiàn)在把上面的例子用代碼實(shí)現(xiàn)下:
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("主線程執(zhí)行完畢----");
}
}
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:
今天寫不完,要下班,明天有時(shí)間寫完
總結(jié)
以上是生活随笔為你收集整理的java中的并发类_java中并发常用工具类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CCIE-LAB-第七篇-IPV6 EI
- 下一篇: java 一元线性回归_一元线性回归的j