多線程中幾個特殊的類

来源:http://www.cnblogs.com/Dylansuns/archive/2017/05/17/6870096.html
-Advertisement-
Play Games

1、FutureTask 2、CyclicBarrier 3、CountDownLatch 4、Semaphore ...


1、FutureTask

 1 package com.ietree.basicskill.mutilthread.OtherClass;
 2 
 3 import java.util.concurrent.*;
 4 
 5 /**
 6  * Created by Administrator on 2017/5/17.
 7  */
 8 public class UseFuture implements Callable<String> {
 9 
10     private String para;
11 
12     public UseFuture(String para){
13         this.para = para;
14     }
15 
16     /**
17      * 這裡是真實的業務邏輯,其執行可能很慢
18      */
19     @Override
20     public String call() throws Exception {
21         //模擬執行耗時
22         Thread.sleep(5000);
23         String result = this.para + "處理完成";
24         return result;
25     }
26 
27     //主控制函數
28     public static void main(String[] args) throws Exception {
29         String queryStr = "query";
30         //構造FutureTask,並且傳入需要真正進行業務邏輯處理的類,該類一定是實現了Callable介面的類
31         FutureTask<String> future = new FutureTask<String>(new UseFuture(queryStr));
32 
33         FutureTask<String> future2 = new FutureTask<String>(new UseFuture(queryStr));
34         //創建一個固定線程的線程池且線程數為1,
35         ExecutorService executor = Executors.newFixedThreadPool(2);
36         //這裡提交任務future,則開啟線程執行RealData的call()方法執行
37         //submit和execute的區別: 第一點是submit可以傳入實現Callable介面的實例對象, 第二點是submit方法有返回值
38 
39         Future f1 = executor.submit(future);        //單獨啟動一個線程去執行的
40         Future f2 = executor.submit(future2);
41         System.out.println("請求完畢");
42 
43         try {
44             //這裡可以做額外的數據操作,也就是主程式執行其他業務邏輯
45             System.out.println("處理實際的業務邏輯...");
46             Thread.sleep(1000);
47         } catch (Exception e) {
48             e.printStackTrace();
49         }
50         //調用獲取數據方法,如果call()方法沒有執行完成,則依然會進行等待
51         System.out.println("數據:" + future.get());
52         System.out.println("數據:" + future2.get());
53 
54         executor.shutdown();
55     }
56 
57 
58 }

2、CyclicBarrier

 1 package com.ietree.basicskill.mutilthread.OtherClass;
 2 
 3 import java.io.IOException;
 4 import java.util.Random;
 5 import java.util.concurrent.BrokenBarrierException;
 6 import java.util.concurrent.CyclicBarrier;
 7 import java.util.concurrent.ExecutorService;
 8 import java.util.concurrent.Executors;
 9 
10 /**
11  * Created by Administrator on 2017/5/17.
12  */
13 public class UseCyclicBarrier {
14 
15     static class Runner implements Runnable {
16         private CyclicBarrier barrier;
17         private String name;
18 
19         public Runner(CyclicBarrier barrier, String name) {
20             this.barrier = barrier;
21             this.name = name;
22         }
23         @Override
24         public void run() {
25             try {
26                 Thread.sleep(1000 * (new Random()).nextInt(5));
27                 System.out.println(name + " 準備OK.");
28                 barrier.await();
29             } catch (InterruptedException e) {
30                 e.printStackTrace();
31             } catch (BrokenBarrierException e) {
32                 e.printStackTrace();
33             }
34             System.out.println(name + " Go!!");
35         }
36     }
37 
38     public static void main(String[] args) throws IOException, InterruptedException {
39         CyclicBarrier barrier = new CyclicBarrier(3);  // 3
40         ExecutorService executor = Executors.newFixedThreadPool(3);
41 
42         executor.submit(new Thread(new Runner(barrier, "zhangsan")));
43         executor.submit(new Thread(new Runner(barrier, "lisi")));
44         executor.submit(new Thread(new Runner(barrier, "wangwu")));
45 
46         executor.shutdown();
47     }
48 
49 }

3、CountDownLatch

 1 package com.ietree.basicskill.mutilthread.OtherClass;
 2 
 3 import java.util.concurrent.CountDownLatch;
 4 
 5 /**
 6  * Created by Administrator on 2017/5/17.
 7  */
 8 public class UseCountDownLatch {
 9 
10     public static void main(String[] args) {
11 
12         final CountDownLatch countDown = new CountDownLatch(2);
13 
14         Thread t1 = new Thread(new Runnable() {
15             @Override
16             public void run() {
17                 try {
18                     System.out.println("進入線程t1" + "等待其他線程處理完成...");
19                     countDown.await();
20                     System.out.println("t1線程繼續執行...");
21                 } catch (InterruptedException e) {
22                     e.printStackTrace();
23                 }
24             }
25         },"t1");
26 
27         Thread t2 = new Thread(new Runnable() {
28             @Override
29             public void run() {
30                 try {
31                     System.out.println("t2線程進行初始化操作...");
32                     Thread.sleep(3000);
33                     System.out.println("t2線程初始化完畢,通知t1線程繼續...");
34                     countDown.countDown();
35                 } catch (InterruptedException e) {
36                     e.printStackTrace();
37                 }
38             }
39         });
40         Thread t3 = new Thread(new Runnable() {
41             @Override
42             public void run() {
43                 try {
44                     System.out.println("t3線程進行初始化操作...");
45                     Thread.sleep(4000);
46                     System.out.println("t3線程初始化完畢,通知t1線程繼續...");
47                     countDown.countDown();
48                 } catch (InterruptedException e) {
49                     e.printStackTrace();
50                 }
51             }
52         });
53 
54         t1.start();
55         t2.start();
56         t3.start();
57     }
58 }

4、Semaphore

 1 package com.ietree.basicskill.mutilthread.OtherClass;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 import java.util.concurrent.Semaphore;
 6 
 7 /**
 8  * Created by Administrator on 2017/5/17.
 9  */
10 public class UseSemaphore {
11 
12     public static void main(String[] args) {
13         // 線程池
14         ExecutorService exec = Executors.newCachedThreadPool();
15         // 只能5個線程同時訪問
16         final Semaphore semp = new Semaphore(5);
17         // 模擬20個客戶端訪問
18         for (int index = 0; index < 20; index++) {
19             final int NO = index;
20             Runnable run = new Runnable() {
21                 public void run() {
22                     try {
23                         // 獲取許可
24                         semp.acquire();
25                         System.out.println("Accessing: " + NO);
26                         //模擬實際業務邏輯
27                         Thread.sleep((long) (Math.random() * 10000));
28                         // 訪問完後,釋放
29                         semp.release();
30                     } catch (InterruptedException e) {
31                     }
32                 }
33             };
34             exec.execute(run);
35         }
36 
37         try {
38             Thread.sleep(10);
39         } catch (InterruptedException e) {
40             e.printStackTrace();
41         }
42         //System.out.println(semp.getQueueLength());
43         // 退出線程池
44         exec.shutdown();
45     }
46 }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 200 OK 請求成功。一般用於GET與POST請求 301 Moved Permanently 永久移動。請求的資源已被永久的移動到新URI,返回信息會包括新的URI,瀏覽器會自動定向到新URI。今後任何新的請求都應使用新的URI代替 302 Found 臨時移動。與301類似。但資源只是臨時被移 ...
  • 分享一個VBA的一個把一個sheet中的多個table(每一個table又hyperlinks),分配在不同的sheet中的方法,做這個真的也是耗費了不少的腦細胞。 Option Explicit ’這個是一個好習慣 ’第一種方法,通過currentregion來判斷區域,但是不是很保險 Sub G ...
  • 本節探討Java中的動態代理,介紹其用法和基本實現原理,利用它實現簡單的AOP框架 ...
  • 一、從石油工程師到IT入門 本人是石油工程師,長期在中東兩伊邊境油田工作,常年漂泊在外。眾所周知,石油行業環境艱苦,長石油的地方不是在鳥不拉屎的沙漠,深山老林,就是在驚濤駭浪的海上平臺。記得第一次到伊拉克邊境的時候,里三層,外三層全是雇佣軍,警察和士兵把手,連井場都不能隨處亂走,因為聽說兩伊戰爭的時 ...
  • https://msdn.microsoft.com/en-us/library/d4cfawwc.aspx For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation. Resou ...
  • 最近對 newlib 中的啟動代碼 crt0 產生了興趣,於是就分析了下其代碼。crt0 的源碼位於 libgloss/arm/crt0.S,為了相容各種 ARM 架構,crt0.S 中有大量的條件判斷巨集定義,對於只關心 ARMv7e-M 的我來說很是痛苦。剛好手上有個基於 STM32F412 的 ...
  • 作業 1: 員工信息表程式,實現增刪改查操作 可進行模糊查詢,語法至少支持下麵3種: select name,age from staff_table where age > 22 select * from staff_table where dept = "IT" select * from s ...
  • 第一次寫博客這玩意,不太會,算了,直接粘代碼吧。 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...