マルチスレッドヘルプクラス(CountDownLatch,Excutor,Executors)
JDK1.5いくつかの重要なスレッドヘルプクラスがあり、ラインプログラムの処理に役立ちます.
CountDownLatch,Executor,Executors,以下は彼らの簡単な使い方です
出力結果
変更実行者数は5、出力結果は:
修正実行者数8、出力結果:
CountDownLatch,Executor,Executors,以下は彼らの簡単な使い方です
package com.tang.test;
import java.util.concurrent.CountDownLatch;
public class Job implements Runnable {
private final CountDownLatch doneSignal;
private final String name;
Job(CountDownLatch doneSignal, String name) {
this.doneSignal = doneSignal;
this.name = name;
}
public void run() {
try {
System.out.println(name + " begin to do his work ");
Thread.sleep(2000);// 2 ,
System.out.println(name + " have done his work ");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
doneSignal.countDown();// -1
}
}
}
package com.tang.test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class DoWork {
private static final int N = 5;
public static void main(String[] args) {
CountDownLatch doneSignal = new CountDownLatch(5);// 5
Executor e = Executors.newFixedThreadPool(2);// 1
for (int i = 0; i < N; ++i)
e.execute(new Job(doneSignal, " worker: "+i));//
try {
doneSignal.await();//
System.out.println("all work have done!");
} catch (InterruptedException e1) {
e1.printStackTrace();
}finally{
System.exit(0);//
}
}
}
出力結果
worker: 0 begin to do his work
worker: 1 begin to do his work
worker: 0 have done his work
worker: 1 have done his work
worker: 2 begin to do his work
worker: 3 begin to do his work
worker: 3 have done his work
worker: 4 begin to do his work
worker: 2 have done his work
worker: 4 have done his work
all work have done!
変更実行者数は5、出力結果は:
worker: 0 begin to do his work
worker: 3 begin to do his work
worker: 1 begin to do his work
worker: 2 begin to do his work
worker: 4 begin to do his work
worker: 4 have done his work
worker: 3 have done his work
worker: 1 have done his work
worker: 2 have done his work
worker: 0 have done his work
all work have done!
修正実行者数8、出力結果:
worker: 0 begin to do his work
worker: 2 begin to do his work
worker: 4 begin to do his work
worker: 1 begin to do his work
worker: 3 begin to do his work
worker: 2 have done his work
worker: 4 have done his work
worker: 3 have done his work
worker: 0 have done his work
worker: 1 have done his work
all work have done!