初学线程的java程序员在学习线程的时候,如果是想使用多线程,要么是继承Thread类,要么是实现runnable接口再提交给一个新创建的Thread。
下面介绍一下使用ThreadPoolExecutor线程执行者来运行多线程任务。它将线程创建与任务运行分离开来。
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadExecuteExample {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; i++) {
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
service.shutdown();
try {
service.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
ExecutorService service = Executors.newFixedThreadPool(2);通过Executors创建了一个拥有两个线程的ExecutorService对象。
for (int i = 0; i < 10; i++) {
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}往ExecutorService中提交了10个runnable对象的实例。ExecutorService会使用内部的2个线程来逐个运行这10个runnable对象。
service.shutdown();关闭执行者。因为ExecutorService利用了它内部的初始化好的线程去执行提交的多个runnable任务,所以这些线程被反复利用而不会消亡。如果不显示的调用shutdown()方法的话,ExecutorService内部的线程一直会存活下去,这样即使任务完成了,虚拟机也不会退出。调用shutdown()后就会通知ExecutorService运行完任务后销毁所有的线程。
shutdown是一个非阻塞的方法。
service.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);在指定的时间内阻塞等待ExecutorService任务的完成。
原文地址:http://blog.csdn.net/ilovezhangxian/article/details/39370121