Java SE5 java.util.concurrent Executors simplify concurrent programming by managing
Thread objects for you. Executors provide a layer of indirection between a client and the
execution of a task; instead of a client executing a task directly, an intermediate object
executes the task. Executors allow you to manage the execution of asynchronous tasks
without having to explicitly manage the lifecycle of threads. Executors are the preferred
method for starting tasks in Java SE5/6.
We can use an Executor instead of explicitly creating Thread objects in
MoreBasicThreads.java. A LiftOff object knows how to run a specific task; like the
Command design pattern, it exposes a single method to be executed. An ExecutorService
(an Executor with a service lifecycle!ae.g., shutdow) knows how to build the appropriate
context to execute Runnable objects. In the following example, the CachedThreadPool
creates one thread per task. Note that an ExecutorService object is created using a static
Executors method which determines the kind of Executor it will be:
package c1;
//Demonstration of the Runnable interface.
import java.util.concurrent.*;
class LiftOff implements Runnable {
protected int countDown = 10; // Default
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff() {}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#" + id + "(" +
(countDown > 0 ? countDown : "Liftoff!") + "), ";
}
public void run() {
while(countDown-- > 0) {
System.out.print(status());
Thread.yield();
}
}
} ///:~ */
//: concurrency/BasicThreads.java
//The most basic use of the Thread class.
public class Test {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 5; i++)
exec.execute(new LiftOff());
exec.shutdown();
}
} /* Output: (90% match)
Waiting for LiftOff
#0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1),
#0(Liftoff!),
*///:~
阅读(540) | 评论(0) | 转发(0) |