Concurrent應用

一般的服務器都需要線程池,比如Web、FTP等服務器,不過它們一般都自己實現了線程池, 比如以前介紹過的Tomcat、 Resin和Jetty等,現在有了JDK5,我們就沒有必要重複造車輪了,直接使用就可以,何況使用也很方便,性能也非常高。

package concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadPool{
public static void main(String args[]) throwsInterruptedException {
// only two threads
ExecutorService exec = Executors.newFixedThreadPool(2);
for(int index = 0; index < 100; index++) {
Runnable run = newRunnable() {
public void run(){
long time =(long)(Math.random() * 1000);
System.out.println(“Sleeping” + time + “ms”);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
// must shutdown
exec.shutdown();
}
}

上面是一個簡單的例子,使用了2個大小的線程池來處理100個線程。但有一個問題:在for 循環的過程中,會等待線程池有空閒的線程,所以主線程會阻塞的。爲了解決這個問題,一般啓動一個線程來做for循環,就是爲了避免由於線程池滿了造成主線 程阻塞。不過在這裏我沒有這樣處理。[重要修正:經過測試,即使線程池大小小於實際線程數大小,線程池也不會阻塞的,這與Tomcat的線程池不同,它將 Runnable實例放到一個“無限”的BlockingQueue中,所以就不用一個線程啓動for循環,Doug Lea果然厲害]

另外它使用了Executors的靜態函數生成一個固定的線程池,顧名思義,線程池的線程是 不會釋放的,即使它是Idle。這就會產生性能問題,比如如果線程池的大小爲200,當全部使用完畢後,所有的線程會繼續留在池中,相應的內存和線程切換(while(true)+sleep循環)都會增加。如果要避免這個問題,就必須直接使用ThreadPoolExecutor()來構造。可以像 Tomcat的線程池一樣設置“最大線程數”、“最小線程數”和“空閒線程keepAlive的時間”。通過這些可以基本上替換Tomcat的線程池實現 方案。

需要注意的是線程池必須使用shutdown來顯式關閉,否則主線程就無法退出。 shutdown也不會阻塞主線程。

許多長時間運行的應用有時候需要定時運行 任務完成一些諸如統計、優化等工作,比如在電信行業中處理用戶話單時,需要每隔1分鐘處理話單;網站每天凌晨統計用戶訪問量、用戶數;大型超時凌晨3點統 計當天銷售額、以及最熱賣的商品;每週日進行數據庫備份;公司每個月的10號計算工資並進行轉帳等,這些都是定時任務。通過 java的併發庫concurrent可 以輕鬆的完成這些任務,而且非常的簡單。

package concurrent;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
public class TestScheduledThread{
public static void main(String[] args) {
final ScheduledExecutorServicescheduler = Executors
.newScheduledThreadPool(2);
final Runnablebeeper = new Runnable() {
int count =0;
public void run(){
System.out.println(newDate() + ”beep ” + (++count));
}
};
// 1秒鐘後運行,並每隔2秒運行一次
final ScheduledFuturebeeperHandle = scheduler.scheduleAtFixedRate(
beeper, 1, 2, SECONDS);
// 2秒鐘後運行,並每次在上次任務運行完後等待5秒後重新運行
final ScheduledFuturebeeperHandle2 = scheduler
.scheduleWithFixedDelay(beeper, 2, 5, SECONDS);
// 30秒後結束關閉任務,並且關閉Scheduler
scheduler.schedule(newRunnable() {
public void run(){
beeperHandle.cancel(true);
beeperHandle2.cancel(true);
scheduler.shutdown();
}
}, 30, SECONDS);
}
}

爲了退出進程,上面的代碼中加入了關閉Scheduler的操作。而對於24小時運行的應用 而言,是沒有必要關閉Scheduler的。

在實際應用中,有時候需要多個 線程同時工作以完成同一件事情,而且在完成過程中,往往會等待其他線程都完成某一階段後再執行,等所有線程都到達某一個階段後再統一執行。

比如有幾個旅行團需要途經深圳、廣州、韶關、長沙最後到達武漢。旅行團中有自駕遊的,有徒步的,有乘坐旅遊大巴的;這些旅行團同時出發,並且每到一個目的地,都要等待其他旅行團到達此地後再同時出發,直到都到達終點站武漢。

這時候CyclicBarrier就 可以派上用場。CyclicBarrier最重要的屬性就是參與者個數,另外最要方法是await()。當所有線程都調用了await()後,就表示這些 線程都可以繼續執行,否則就會等待。

package concurrent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCyclicBarrier{
// 徒步需要的時間: Shenzhen, Guangzhou, Shaoguan, Changsha, Wuhan
private static int[] timeWalk = { 5, 8, 15, 15, 10 };
// 自駕遊
private static int[] timeSelf = { 1, 3, 4, 4, 5 };
// 旅遊大巴
private static int[] timeBus = { 2, 4, 6, 6, 7 };

static Stringnow() {
SimpleDateFormat sdf = new SimpleDateFormat(“HH:mm:ss”);
return sdf.format(new Date()) + “: “;
}

static class Tour implementsRunnable {
private int[]times;
private CyclicBarrierbarrier;
private StringtourName;
public Tour(CyclicBarrierbarrier, String tourName, int[] times) {
this.times= times;
this.tourName= tourName;
this.barrier= barrier;
}
public void run(){
try {
Thread.sleep(times[0] * 1000);
System.out.println(now() + tourName + ” Reached Shenzhen”);
barrier.await();
Thread.sleep(times[1] * 1000);
System.out.println(now() + tourName + ” Reached Guangzhou”);
barrier.await();
Thread.sleep(times[2] * 1000);
System.out.println(now() + tourName + ” Reached Shaoguan”);
barrier.await();
Thread.sleep(times[3] * 1000);
System.out.println(now() + tourName + ” Reached Changsha”);
barrier.await();
Thread.sleep(times[4] * 1000);
System.out.println(now() + tourName + ” Reached Wuhan”);
barrier.await();
} catch (InterruptedException e) {
} catch (BrokenBarrierException e) {
}
}
}

public static void main(String[] args) {
// 三個旅行團
CyclicBarrier barrier = new CyclicBarrier(3);
ExecutorService exec = Executors.newFixedThreadPool(3);
exec.submit(newTour(barrier, “WalkTour”, timeWalk));
exec.submit(newTour(barrier, “SelfTour”, timeSelf));
exec.submit(newTour(barrier, “BusTour”, timeBus));
exec.shutdown();
}
}

運行結果:
00:02:25: SelfTour Reached Shenzhen
00:02:25: BusTour Reached Shenzhen
00:02:27: WalkTour Reached Shenzhen
00:02:30: SelfTour Reached Guangzhou
00:02:31: BusTour Reached Guangzhou
00:02:35: WalkTour Reached Guangzhou
00:02:39: SelfTour Reached Shaoguan
00:02:41: BusTour Reached Shaoguan

併發庫中的BlockingQueue是 一個比較好玩的類,顧名思義,就是阻塞隊列。該類主要提供了兩個方法put()和take(),前者將一個對象放到隊列中,如果隊列已經滿了,就等待直到有空閒節點;後者從head取一個對象,如果沒有對象,就等待直到有可取的對象。

下面的例子比較簡單,一個讀線程,用於將要處理的文件對象添加到阻塞隊列中,另外四個寫線程用於取出文件對象,爲了模擬寫操作耗時長的特點,特讓線程睡眠一段隨機長度的時間。另外,該Demo也使用到了線程池和原子整型(AtomicInteger),AtomicInteger可以在併發情況下達到原子化更新,避免使用了synchronized,而且性能非常高。由 於阻塞隊列的put和take操作會阻塞,爲了使線程退出,特在隊列中添加了一個“標識”,算法中也叫“哨兵”,當發現這個哨兵後,寫線程就退出。

當然線程池也要顯式退出了。

package concurrent;
import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class TestBlockingQueue {
static long randomTime(){
return (long) (Math.random()* 1000);
}

public static void main(String[] args) {
// 能容納100個文件
final BlockingQueuequeue = new LinkedBlockingQueue(100);
// 線程池
final ExecutorServiceexec = Executors.newFixedThreadPool(5);
final Fileroot = new File(“F:\\JavaLib”);
// 完成標誌
final FileexitFile = new File(“”);
// 讀個數
final AtomicIntegerrc = new AtomicInteger();
// 寫個數
final AtomicIntegerwc = new AtomicInteger();
// 讀線程
Runnable read = newRunnable() {
public void run(){
scanFile(root);
scanFile(exitFile);
}

public void scanFile(File file) {
if (file.isDirectory()){
File[] files = file.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory()
|| pathname.getPath().endsWith(“.java”);
}
});
for (Fileone : files)
scanFile(one);
} else {
try {
int index =rc.incrementAndGet();
System.out.println(“Read0:” + index + ”“
+ file.getPath());
queue.put(file);
} catch (InterruptedException e) {
}
}
}
};
exec.submit(read);
// 四個寫線程
for (int index = 0; index < 4; index++) {
// write thread
final int NO= index;
Runnable write = newRunnable() {
String threadName = “Write”+ NO;
public void run(){
while (true) {
try {
Thread.sleep(randomTime());
int index =wc.incrementAndGet();
File file = queue.take();
// 隊列已經無對象
if (file ==exitFile) {
// 再次添加”標誌”,以讓其他線程正常退出
queue.put(exitFile);
break;
}
System.out.println(threadName + “: ” + index + ” “
+ file.getPath());
} catch (InterruptedException e) {
}
}
}
};
exec.submit(write);
}
exec.shutdown();
}
}

從名字可以看出,CountDownLatch是 一個倒數計數的鎖,當倒數到0時觸發事件,也就是開鎖,其他人就可以進入了。在一些應用場合中,需要等待某個條件達到要求後才能做後面的事情;同時當線程都完成後也會觸發事件,以便進行後面的操作。

CountDownLatch最重要的方法是countDown()和await(),前者 主要是倒數一次,後者是等待倒數到0,如果沒有到達0,就只有阻塞等待了。

一個CountDouwnLatch實例是不能重複使用的,也就是說它是一次性的,鎖一經被 打開就不能再關閉使用了,如果想重複使用,請考慮使用CyclicBarrier

下面的例子簡單的說明了CountDownLatch的使用方法,模擬了100米賽跑,10 名選手已經準備就緒,只等裁判一聲令下。當所有人都到達終點時,比賽結束。

同樣,線程池需要顯式shutdown。

package concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestCountDownLatch {
public static void main(String[] args) throwsInterruptedException {
// 開始的倒數鎖
final CountDownLatchbegin = new CountDownLatch(1);
// 結束的倒數鎖
final CountDownLatchend = new CountDownLatch(10);
// 十名選手
final ExecutorServiceexec = Executors.newFixedThreadPool(10);
for(int index = 0; index < 10; index++) {
final int NO= index + 1;
Runnable run = newRunnable(){
public void run(){
try {
begin.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println(“No.”+ NO + ”arrived”);
} catch (InterruptedException e) {
} finally {
end.countDown();
}
}
};
exec.submit(run);
}
System.out.println(“GameStart”);
begin.countDown();
end.await();
System.out.println(“GameOver”);
exec.shutdown();
}
}

運行結果:
Game Start
No.4 arrived
No.1 arrived
No.7 arrived
No.9 arrived
No.3 arrived
No.2 arrived
No.8 arrived
No.10 arrived
No.6 arrived
No.5 arrived
Game Over

有時候在實際應用中,某些操作很耗時,但 又不是不可或缺的步驟。比如用網頁瀏覽器瀏覽新聞時,最重要的是要顯示文字內容,至於與新聞相匹配的圖片就沒有那麼重要的,所以此時首先保證文字信息先顯示,而圖片信息會後顯示,但又不能不顯示,由於下載圖片是一個耗時的操作,所以必須一開始就得下載。

Java的並 發庫Future類 就可以滿足這個要求。Future的重要方法包括get()和cancel(),get()獲取數據對象,如果數據沒有加載,就會阻塞直到取到數據,而 cancel()是取消數據加載。另外一個get(timeout)操作,表示如果在timeout時間內沒有取到就失敗返回,而不再阻塞。

下面的Demo簡單的說明了Future的使用方法:一個非常耗時的操作必須一開始啓動,但又不能一直等待;其他重要的事情又必須做,等完成後,就可以做不重要的事情。

package concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestFutureTask {
public static void main(String[] args)throwsInterruptedException,
ExecutionException {
final ExecutorServiceexec = Executors.newFixedThreadPool(5);
Callable call = newCallable() {
public Stringcall() throws Exception {
Thread.sleep(1000 * 5);
return “Otherless important but longtime things.”;
}
};
Future task = exec.submit(call);
// 重要的事情
Thread.sleep(1000 * 3);
System.out.println(“Let’sdo important things.”);
// 其他不重要的事情
String obj = task.get();
System.out.println(obj);
// 關閉線程池
exec.shutdown();
}
}

運行結果:
Let’s do important things.
Other less important but longtime things.

考慮以下場景:瀏覽網頁時,瀏覽器了5個 線程下載網頁中的圖片文件,由於圖片大小、網站訪問速度等諸多因素的影響,完成圖片下載的時間就會有很大的不同。如果先下載完成的圖片就會被先顯示到界面上,反之,後下載的圖片就後顯示。

Java的並 發庫CompletionService可 以滿足這種場景要求。該接口有兩個重要方法:submit()和take()。submit用於提交一個runnable或者callable,一般會提 交給一個線程池處理;而take就是取出已經執行完畢runnable或者callable實例的Future對象,如果沒有滿足要求的,就等待了。 CompletionService還有一個對應的方法poll,該方法與take類似,只是不會等待,如果沒有滿足要求,就返回null對象。

package concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestCompletionService {
public static void main(String[] args) throwsInterruptedException,
ExecutionException {
ExecutorService exec = Executors.newFixedThreadPool(10);
CompletionService serv =
new ExecutorCompletionService(exec);

for (int index = 0; index < 5;index++) {
final int NO= index;
Callable downImg = newCallable() {
public Stringcall() throws Exception {
Thread.sleep((long) (Math.random() * 10000));
return “DownloadedImage ” + NO;
}
};
serv.submit(downImg);
}

Thread.sleep(1000 * 2);
System.out.println(“Showweb content”);
for (int index = 0; index < 5; index++) {
Future task = serv.take();
String img = task.get();
System.out.println(img);
}
System.out.println(“End”);
// 關閉線程池
exec.shutdown();
}
}

運行結果:
Show web content
Downloaded Image 1
Downloaded Image 2
Downloaded Image 4
Downloaded Image 0
Downloaded Image 3
End

操作系統的信號量是個很重要的概念,在進程控制方面都有應用。Java並 發庫Semaphore可 以很輕鬆完成信號量控制,Semaphore可以控制某個資源可被同時訪問的個數,acquire()獲取一個許可,如果沒有就等待,而 release()釋放一個許可。比如在Windows下可以設置共享文件的最大客戶端訪問個數。

Semaphore維護了當前訪問的個數,提供同步機制,控制同時訪問的個數。在數據結構中 鏈表可以保存“無限”的節點,用Semaphore可以實現有限大小的鏈表。另外重入鎖ReentrantLock也可以實現該功能,但實現上要負責些, 代碼也要複雜些。

下面的Demo中申明瞭一個只有5個許可的Semaphore,而有20個線程要訪問這個資 源,通過acquire()和release()獲取和釋放訪問許可。

package concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class TestSemaphore {
public static void main(String[] args) {
// 線程池
ExecutorService exec =Executors.newCachedThreadPool();
// 只能5個線程同時訪問
final Semaphoresemp = new Semaphore(5);
// 模擬20個客戶端訪問
for (int index = 0; index < 20; index++) {
final int NO= index;
Runnable run = newRunnable() {
public void run(){
try {
// 獲取許可
semp.acquire();
System.out.println(“Accessing:” + NO);
Thread.sleep((long) (Math.random() * 10000));
// 訪問完後,釋放
semp.release();
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
// 退出線程池
exec.shutdown();
}
}

運行結果:
Accessing: 0
Accessing: 1
Accessing: 2
Accessing: 3
Accessing: 4
Accessing: 5
Accessing: 6
Accessing: 7
Accessing: 8
Accessing: 9
Accessing: 10
Accessing: 11
Accessing: 12
Accessing: 13
Accessing: 14
Accessing: 15
Accessing: 16
Accessing: 17
Accessing: 18
Accessing: 19

 --------------------------------------------------------

concurrent:(readWriteLock,ReentrantLock,Atomic,CountDownLatch)
1,接口Executor 是一個簡單的標準化接口,用於定義類似於線程的自定義子系統,包括線程池、異步 IO 和輕量級任務框架
2,隊列: java.util.concurrent ConcurrentLinkedQueue 類提供了高效的、可伸縮的、線程安全的非阻塞 FIFO 隊列。
3,計時:TimeUnit 類爲指定和控制基於超時的操作提供了多重粒度(包括納秒級)
4,同步器
  四個類可協助實現常見的專用同步語句。Semaphore 是一個經典的併發工具。CountDownLatch 是一個極其簡單但又極其常用的實用工具,用於在保持給定數目的信號、事件或條件前阻塞執行。CyclicBarrier 是一個可重置的多路同步點,在某些並行編程風格中很有用。Exchanger 允許兩個線程在集合點交換對象,它在多流水線設計中是有用的。
5,併發 Collection
  除隊列外,此包還提供了幾個設計用於多線程上下文中的 Collection 實現:ConcurrentHashMap、CopyOnWriteArrayList 和 CopyOnWriteArraySet。
  此包中與某些類一起使用的“Concurrent&rdquo前綴;是一種簡寫,表明與類似的“同步”類有所不同。例如,java.util.Hashtable 和 Collections.synchronizedMap(new HashMap()) 是同步的,但 ConcurrentHashMap 則是“併發的”。併發集合是線程安全的,但是不受單個排他鎖定的管理。在 ConcurrentHashMap 這一特定情況下,它可以安全地允許進行任意數目的併發讀取,以及數目可調的併發寫入。需要通過單個鎖定阻止對集合的所有訪問時,“同步”類是很有用的,其代價是較差的可伸縮性。在期望多個線程訪問公共集合的其他情況中,通常“併發”版本要更好一些。當集合是未共享的,或者僅保持其他鎖定時集合是可訪問的情況下,非同步集合則要更好一些。
  大多數併發 Collection 實現(包括大多數 Queue)與常規的 java.util 約定也不同,因爲它們的迭代器提供了弱一致的,而不是快速失敗的遍歷。弱一致的迭代器是線程安全的,但是在迭代時沒有必要凍結集合,所以它不一定反映自迭代器創建以來的所有更新。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章