歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java1.5後的多線程框架

Java1.5後的多線程框架

日期:2017/3/1 9:48:27   编辑:Linux編程

內容主要包括之Executors,Executor,ExecutorService,CompletionService,Future,CountDownLauch,Callable,Runnable

在講1.5之後的多線程模式之前,先簡單的說一下1.5之前的線程模式,簡單的說就是Thread+Runnable模式。Thread是線程,Runnable可以看做是線程要執行的任務。1.5之前的線程模式的一些缺點:

1 管理多線程有諸多不便,比如:多個線程創建,需要多次new Thread;線程生命周期的管理,和多線程同步,需要對Java多線程的實現有比較深入的了解

2 Runnable沒有結果返回,需要某種機制等待線程執行結束,通過通知或者回調獲取線程執行的結果

Executors線程框架
由於時間關系,UML簡化了,這裡畫出了本人認為最重要的幾個類

類的簡要說明
Executors
可以看做是工廠類,主要用於創建和管理Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable

interface ExecutrService
個人覺得看以把ExecutorService看成是多線程的容器,主要用於管理多線程,可以往容器中提交線程,由容器負責線程的生命周期,包括啟動,執行,結束線程. 通過上面的類圖可以看到我們可以往容器中提交實現Callable或者Runnable接口的類;往容器中提交Callable的實例,將會返回一個Future的對象,這個Future對象可以用於簡單的控制Callable對應的線程

interface Callable
跟Runable類似,同樣是封裝了線程需要的執行任務,執行任務在Callable的call方法中實現,call方法可以看成是Runnable的run方法,唯一不同的是call方法,有一個返回值。我們知道call或者run方法,是由線程框架自己去調用的,那麼線程執行結束之後,我們如何獲取call方法的返回值呢?我們知道,當往容器中提交Callable實例時,會返回Future類的一個實例。通過Future類的實例,我們可以獲取線程結束後(也就是call函數執行完畢)的返回值

interface Future
這個類的基本功能其實在ExecutorService和Callable中已經有提到了,每次往容器中提交Callable或者Runnable任務,都會返回Future的實例;該實例可以簡單的管理執行Callable或者Runnable的線程,主要用於獲取線程的執行結果,或者查看線程的當前執行狀態

interface CompletionService<V>
當我們向容器中提交多個任務時,建設我們提交任務的順序是task1,task2,task3,我們知道容器是多線程執行任務的,所以任務完成的順序有可能和任務提交的順序不一樣,比如任務完成的順序有可能是task2,task1,task3;CompletionService提供了一種機制,可以理解成維護了一個任務完成隊列,當容器中有任務完成時,會加入到CompletionService的完成隊列中,那麼我們通過CompletionService的take 或者 poll方法,每次都能獲取剩余任務中,最先執行完的任務

Interface ScheduledExecutorService
用於定時,周期性的執行某一個任務,某些情況下可以代替Timer類

CountDownLatch
這個類在類圖中沒有畫出來,主要用於多線程之間的同步。有點類似Semaphore,當計數值等於0時,將觸發事件。

舉例1:

Executor executor = Executors.newFixedThreadPool(10);
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("task executing");
}
};
executor.execute(task);

executor = Executors.newScheduledThreadPool(10);
ScheduledExecutorService scheduler = (ScheduledExecutorService) executor;
scheduler.scheduleAtFixedRate(task, 10, 10, TimeUnit.SECONDS);

舉例2:

/**
* 內核多線程求和,將數據劃分成多個數據塊,每個數據塊交給一個cpu內核線程去計數和,最後在匯總所有數據的和
**/
public class ConcurrentCalculator {
private ExecutorService exec;
private CompletionService<Long> completionService;
private int cpuCoreNumber;
class SumCalculator implements Callable<Long> {
private int[] numbers;
private int start;
private int end;
public SumCalculator(final int[] numers, int start, int end) {
this.numbers = numbers;
this.start = start;
this.end = end;
}
public Long call() throws Exception {
Long sum = 0l;
for (int i = start; i < end; i++) {
sum += numbers[i];
}
return sum;
}
}
public ConcurrentCalculator() {
cpuCoreNumber = Runtime.getRuntime().availableProcessors();
exec = Executors.newFixedThreadPool(cpuCoreNumber);
completionService = new ExecutorCompletionService<Long>(exec);
}
public Long sum(final int[] numbers) {
// 根據CPU核心個數拆分任務,創建FutureTask並提交到Executor
for (int i = 0; i < cpuCoreNumber; i++) {
int increment = numbers.length / cpuCoreNumber + 1;
int start = increment * i;
int end = increment * i + increment;
if (end > numbers.length)
end = numbers.length;
SumCalculator subCalc = new SumCalculator(numbers, start, end);
if (!exec.isShutdown()) {
completionService.submit(subCalc);
}
}
return getResult();
}
/**
* 迭代每個只任務,獲得部分和,相加返回
*
* @return
*/
public Long getResult() {
Long result = 0l;
for (int i = 0; i < cpuCoreNumber; i++) {
try {
Long subSum = completionService.take().get();
result += subSum;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
return result;
}
public void close() {
exec.shutdown();
}
}

舉例3:

public class CountDownLatchDemo
{
private static final int PLAYER_AMOUNT = 5
public CountDownLatchDemo()
{
// TODO Auto-generated constructor stub
}
public void test()
{
//對於每位運動員,CountDownLatch減1後即結束比賽
CountDownLatch begin = new CountDownLatch(1);
//對於整個比賽,所有運動員結束後才算結束
CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
Player[] plays = new Player[PLAYER_AMOUNT];
for(int i=0;i<PLAYER_AMOUNT;i++)
plays[i] = new Player(i+1,begin,end);
//設置特定的線程池,大小為5
ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
for(Player p:plays)
exe.execute(p); //分配線程
System.out.println("Race begins!");
begin.countDown();
try{
end.await(); //等待end狀態變為0,即為比賽結束
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("Race ends!");
}
exe.shutdown();
}
public class Player implements Runnable
{
private int id;
private CountDownLatch begin;
private CountDownLatch end;
public Player(int i, CountDownLatch begin, CountDownLatch end) {
// TODO Auto-generated constructor stub
super();
this.id = i;
this.begin = begin;
this.end = end;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
begin.await(); //等待begin的狀態為0
Thread.sleep((long)(Math.random()*100)); //隨機分配時間,即運動員完成時間
System.out.println("Play"+id+" arrived.");
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
end.countDown(); //使end狀態減1,最終減至0
}
}
}
}

Copyright © Linux教程網 All Rights Reserved