Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2044668
  • 博文数量: 519
  • 博客积分: 10070
  • 博客等级: 上将
  • 技术积分: 3985
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-29 14:05
个人简介

只问耕耘

文章分类

全部博文(519)

文章存档

2016年(1)

2013年(5)

2011年(46)

2010年(220)

2009年(51)

2008年(39)

2007年(141)

2006年(16)

我的朋友

分类: Java

2010-01-18 16:03:29

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!),
*///:~
阅读(507) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~