[Java] 纯文本查看 复制代码
public class ThreadPoolTest {
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
/**
* execute(Runnable x) 没有返回值。可以执行任务,但无法判断任务是否成功完成。
*/
// pool.execute(new RunnableTest("Task1"));
/**
* submit(Runnable x) 返回一个future。可以用这个future来判断任务是否成功完成。
*/
Future future = pool.submit(new RunnableTest("Task2"));
try {
// 阻塞
// start
// 100s 50
// end
// 1.监听任务是否执行完成
// 2.处理任务执行过程中抛出的相关异常
System.out.println(System.currentTimeMillis());
future.get();// 2s
System.out.println(System.currentTimeMillis());
System.out.println("任务完成");
} catch (InterruptedException e) {
} catch (ExecutionException e) {
// 否则我们可以看看任务失败的原因是什么
System.out.println(e.getCause().getMessage());
}
}
}
class RunnableTest implements Runnable {
private String taskName;
public RunnableTest(final String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println("Inside " + taskName + " begin");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Inside " + taskName + " end");
throw new RuntimeException("RuntimeException from inside " + taskName);
}
}