Java中使用Executors创建和管理线程
时间:2011-03-24 zhangjunhd
1. 类 Executors
此类中提供的一些方法有:
1.1 public static ExecutorService newCachedThreadPool ()
创建一个可根据需要创建新线程的线程池,但是在以前构造的 线程可用时将重用它们。对于执行很多短期异步任务的程序而言, 这些线程池通常可提高程序性能。
1.2 public static ExecutorService newFixedThreadPool (intnThreads)
创建一个可重用固定线程数的线程池,以共享的无界队列方式 来运行这些线程。
1.3 public static ExecutorService newSingleThreadExecutor()
创建一个使用单个 worker 线程的 Executor,以无界队列方式 来运行该线程。
这三个方法都可以配合接口ThreadFactory的实例一起使用。并 且返回一个ExecutorService接口的实例。
2. 接口 ThreadFactory
根据需要创建新线程的对象。使用线程工厂就无需再手工编写 对 new Thread 的调用了,从而允许应用程序使用特殊的线程子类 、属性等等。
此接口最简单的实现就是:
class SimpleThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new Thread(r);
}
}
3. 接口ExecutorService
该接口提供了管理终止的方法。
4.创建标准线程池启动线程
4.1 提供一个简单的实现Runnable接口的线程
MyThread.java
package com.zj.concurrency.executors;
public class MyThread implements Runnable {
private int count = 1, number;
public MyThread(int num) {
number = num;
System.out.println("Create Thread-" + number);
}
public void run() {
while (true) {
System.out.println("Thread-" + number + " run " + count+" time(s)");
if (++count == 3)
return;
}
}
}
这个线程会打印出相应的创建和执行信息。
Java中使用Executors创建和管理线程(2)
时间:2011-03-24 zhangjunhd
4.2 使用CachedThreadPool启动线程
CachedThreadPool.java
package com.zj.concurrency.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPool {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++)
exec.execute(new MyThread(i));
exec.shutdown();
}
}
结果:
Create Thread-0
Create Thread-1
Create Thread-2
Create Thread-3
Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Create Thread-4
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
4.3 使用FixedThreadPool启动线程
FixedThreadPool.java
package com.zj.concurrency.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPool {
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++)
exec.execute(new MyThread(i));
exec.shutdown();
}
}
结果:
Create Thread-0
Create Thread-1
Create Thread-2
Create Thread-3
Create Thread-4
Thread-0 run 1 time(s)
Thread-0 ru
|