java.util.concurrent.executor
接口是支持启动新任务的一个简单接口。
序号 | 方法 | 描述 |
---|---|---|
1 | void execute(runnable command) |
在将来的某个时间执行给定的命令。 |
以下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();
}
}
}
}
执行上面代码,得到如下结果 -
running task!
task completed