激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - java并發(fā)包中CountDownLatch和線程池的使用詳解

java并發(fā)包中CountDownLatch和線程池的使用詳解

2021-08-09 10:40chen_yuxi Java教程

這篇文章主要介紹了java并發(fā)包中CountDownLatch和線程池的使用詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

1.CountDownLatch

現(xiàn)在做的這個(gè)華為云TaurusDB比賽中,參考的之前參加過阿里的PolarDB大賽的兩個(gè)大佬的代碼,發(fā)現(xiàn)都有用到CountDownLatch這個(gè)類,之前看代碼的時(shí)候也看過,但是沒有搞得很明白,自己寫也寫不出來,在此自己先學(xué)習(xí)一下。

字面理解:CountDownLatch:數(shù)量減少的門栓。

創(chuàng)建這樣一個(gè)門栓

?
1
CountDownLatch countDownLatch = new CountDownLatch(count);

參數(shù):count,門栓的計(jì)數(shù)次數(shù)。

在所有線程執(zhí)行完成之前,調(diào)用countDownLatch.await()阻塞主線程。

每當(dāng)一個(gè)線程執(zhí)行完一個(gè)指定動作之后,count就會減少1,當(dāng)count等于0時(shí),主線程不再阻塞,開始繼續(xù)執(zhí)行下面的代碼,當(dāng)count大于0時(shí),主線程一直阻塞,等待count變?yōu)?。每個(gè)線程動作執(zhí)行結(jié)束后,執(zhí)行countDownLatch.countDown(),這個(gè)門栓的count減一。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int ThreadNum = 16;
CountDownLatch countDownLatch = new CountDownLatch(ThreadNum);
for(int i = 0; i < ThreadNum ; i++){
 final int finalI = i;
 new Thread(() -> {
  int n = 0;
  System.out.println("線程應(yīng)該做的事情");
  while(n < 10){
   n++;
  }
  countDownLatch.countDown();
 }).start();
}
try{
 countDownLatch.await();
}catch(InterruptedException e){
 logger.infor("InterruptedException!!");
}

 

2.線程池

其實(shí)線程池之前的ipv6的項(xiàng)目里用過,但是也忘記得差不多了,復(fù)習(xí)一下。

線程在創(chuàng)建和關(guān)閉時(shí)都需要花費(fèi)時(shí)間,如果為每一個(gè)小的任務(wù)都創(chuàng)建一個(gè)線程,可能創(chuàng)建和銷毀線程所用的時(shí)間會多于該線程真實(shí)工作所消耗的時(shí)間,就會得不償失。除了時(shí)間,空間也需要考慮,線程本身也是要占用內(nèi)存空間的,大量的線程會食用過多的內(nèi)存資源,可能會造成OOM。另外在回收時(shí),大量的線程會延長GC的停頓時(shí)間。

因此在生產(chǎn)環(huán)境中使用線程必須對其加以控制和管理

使用線程池之后,創(chuàng)建線程變成了從線程池中獲得空閑的線程,關(guān)閉線程變成了歸還線程給線程池。

通過ThreadPoolExecutor可以創(chuàng)建一個(gè)線程池,ThreadPoolExecutor實(shí)現(xiàn)了Executors接口。

舉個(gè)栗子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPoolTest {
 public static void main(String[] args) {
  ThreadPoolExecutor pool = new ThreadPoolExecutor(10,20,60,
    TimeUnit.SECOUNDS,new ArrayBlockingQueue<Runnable>(15000),new ThreadFactory(){
   private AtomicInteger threadId = new AtomicInteger(0);
   @Override
   public Thread newThread(Runnable r){
    Thread thread = new Thread(r);
    thread.setDaemon(true);
    String prefix = "thread-";
    thread.setName(prefix+threadId.incrementAndGet());
    return thread;
   }
  });
 }
}

 

這樣就創(chuàng)建了一個(gè)線程池。參數(shù)依次解釋:

corePoolSize:指定了線程池中線程的數(shù)量,線程池中可以有10個(gè)存活的線程

maximumPoolSize:指定了線程池中最大的線程數(shù),線程池中最多能有20個(gè)存活的線程

keepAliveTime:當(dāng)線程池中的數(shù)量超過corePoolSize時(shí),這些線程在多長時(shí)間會被銷毀,60s

unit:keepAliveTime的單位

workQueue:任務(wù)隊(duì)列,被提交但是沒有被執(zhí)行的任務(wù)存在的地方。他是一個(gè)BlockingQueue<Runnable>接口的對象。

threadFactory:線程工廠,你想創(chuàng)建什么樣子的線程

重點(diǎn)說一下workQueue:

根據(jù)隊(duì)列的功能分類,可以使用以下幾種BlockingQueue接口

補(bǔ)充:Java中CountDownLatch,CyclicBarrier以及Semaphore的使用場景

Java并發(fā)包中提供了很多有用的工具類來幫助開發(fā)者進(jìn)行并發(fā)編程,今天我就來說說CountDownLatch,CyclicBarrier以及Semaphore這三個(gè)的用法和使用場景。

1.CountDownLatch使用場景和用法

CountDownLatch一般是用于某個(gè)線程等待其他線程執(zhí)行完之后,它才能執(zhí)行。例如一家人在等待爸爸媽媽回家,才能進(jìn)行晚宴,示例代碼如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class CountDownLatchTest {
 
 public static void main(String[] args) throws Exception {
  final CountDownLatch cdl = new CountDownLatch(2);
  new Thread(){
   public void run() {
    try {
     System.out.println("等待老爸回家...");
     Thread.sleep(5000);
     cdl.countDown();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    
   };
  }.start();
  
  new Thread(){
   public void run() {
    try {
     System.out.println("等待老媽回家...");
     Thread.sleep(5000);
     cdl.countDown();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   };
  }.start();
  
  cdl.await();
  System.out.println("老爸老媽回來了...");
  System.out.println("晚宴開始了...");
 }
 
}

2.CyclicBarrier(柵欄)使用場景和用法

CyclicBarrier一般是一組線程等待至某個(gè)狀態(tài),然后這一組線程才能同時(shí)執(zhí)行(感覺跟CountDownLatch有點(diǎn)類似啊,不過仔細(xì)想想還是有差別的,感覺容易混淆)。

代碼示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class CyclicBarrierTest {
 
 public static void main(String[] args) {
  int count = 3;
  CyclicBarrier cb = new CyclicBarrier(count, new Runnable() {
   @Override
   public void run() {
    //此處所有線程都調(diào)用了await方法之后,會走到這里
    System.out.println("所有線程操作完成之后都調(diào)用了await方法");
   }
  });
  
  for(int i=0;i<count;i++){
   new WriteLogHandler(cb).start();
  }
 }
 
 static class WriteLogHandler extends Thread{
  
  private CyclicBarrier cb = null;
  
  public WriteLogHandler(CyclicBarrier cb) {
   this.cb = cb;
  }
  
  @Override
  public void run() {
   try {
    System.out.println("線程:" + Thread.currentThread().getName() + "開始寫日志");
    Thread.sleep(2000);
    System.out.println("線程:" + Thread.currentThread().getName() + "寫日志結(jié)束,等待其他線程");
    cb.await();
    
    System.out.println("所有線程寫日志數(shù)據(jù)結(jié)束,繼續(xù)其他操作");
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
 }
 
}

3.Semaphore(信號量)使用場景和用法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Semaphore類似鎖的用法,用于控制對某資源的訪問權(quán)限,示例代碼如下:
public class SemaphoreTest {
 
 public static void main(String[] args) {
  ExecutorService executor = Executors.newCachedThreadPool();
  final Semaphore semaphore = new Semaphore(5);
  
  for(int i=0;i<10;i++){
   final int num = i;
   executor.execute(new Runnable() {
    @Override
    public void run() {
     try {
      semaphore.acquire();
      System.out.println("正在執(zhí)行任務(wù)" + num);
      Thread.sleep((long)Math.random() * 1000);
      System.out.println("任務(wù)" + num + "執(zhí)行結(jié)束");
      semaphore.release();
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   });
  }
  executor.shutdown();
 }
 
}

以上就是這三個(gè)并發(fā)工具類的使用場景和示例,僅為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。歡迎大家一起交流。

原文鏈接:https://blog.csdn.net/chen_yuxi/article/details/97847857

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 免费观看一级欧美大 | 91精品播放| 懂色粉嫩av久婷啪 | 性生活香蕉视频 | 久草在线观看首页 | 久草经典视频 | 成年人国产视频 | 亚洲第一页综合 | 成人免费看视频 | 久久免费观看一级毛片 | 久久久久久久一区二区 | 中文字幕在线免费播放 | 成年人视频在线免费观看 | 一级黄色片在线看 | 免费在线观看成人av | 日本s级毛片免费观看 | 久久久久久久久久久久久国产精品 | 99久久久国产精品免费观看 | 国产在线观看福利 | 美女羞羞视频在线观看 | 成人福利在线免费观看 | 性 毛片 | 韩国十九禁高潮床戏在线观看 | 国产一级免费在线视频 | 久久丝袜脚交足黄网站免费 | 久精品久久 | 万圣街在线观看免费完整版 | 久久久久国产一区二区三区不卡 | 手机av在线电影 | 日韩精品 | 黄色片视频在线观看 | 欧美成人国产va精品日本一级 | 91香蕉国产亚洲一区二区三区 | 高潮娇喘嗯啊~文字 | 久久成人国产精品 | 久久久久免费精品国产小说色大师 | 久久精品网站视频 | 青青草成人免费视频在线 | 精品国产91久久久久久久 | 视频一区二区视频 | av在线一区二区三区四区 |