Java Executor接口
1 Executor接口的介绍
java.util.concurrent.Executor接口是支持启动新任务的一个简单接口。
2 Executor接口的方法
方法 | 描述 |
---|---|
void execute(Runnable command) | 在将来的某个时间执行给定的命令。 |
3 Executor接口的案例
以下TestThread程序显示了如何在基于线程的环境中Executor接口的用法。
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
Executor executor = Executors.newCachedThreadPool();
executor.execute(new Task());
ThreadPoolExecutor pool = (ThreadPoolExecutor)executor;
pool.shutdown();
}
static class Task implements Runnable {
public void run() {
try {
Long duration = (long) (Math.random() * 5);
System.out.println("Running Task!");
TimeUnit.SECONDS.sleep(duration);
System.out.println("Task Completed");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
输出结果为:
Running Task!
Task Completed
热门文章
优秀文章