执行者(Executor)
优质
小牛编辑
128浏览
2023-12-01
java.util.concurrent.Executor接口是一个支持启动新任务的简单接口。
ExecutorService方法
Sr.No. | 方法和描述 |
---|---|
1 | void execute(Runnable command) 在将来的某个时间执行给定的命令。 |
例子 (Example)
以下TestThread程序显示了基于线程的环境中Executor接口的使用。
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();
}
}
}
}
这将产生以下结果。
输出 (Output)
Running Task!
Task Completed