JDK1.5有几个很重要的线程帮助类,对处理线程序很有帮助,他们分别是
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!