我是Java并发包的新手,想要尝试使用ExecutorService来控制线程的执行时间。
因此,对于一个继续运行的线程MyThread,我想使用ExecutorService和Future类在2秒后停止它。
public class MyThread extends Thread {
public static int count = 0;
@Override
public void run() {
while (true) {
System.out.println(count++);
}
}
}
public static void main(String[] args) throws IOException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
MyThread thread = new MyThread();
FutureTask<String> futureTask = new FutureTask<String>(thread, "success");
try {
executorService.submit(futureTask).get(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
System.out.println("timeout");
e.printStackTrace();
executorService.shutdownNow();
}
}
然而,线程在2秒后仍然保持打印数字。如何在不更改MyThread类本身的情况下控制线程?
答案 0 :(得分:0)
答案 1 :(得分:0)
使用ExecutorService
的主要目的是隐藏如何为程序员创建,重用和一般管理线程。
您需要实施MyThread
:
Runnable
public class MyRunnable implements Runnable {
private int count = 0;
public void run() {
while (true) {
System.out.println(count++);
}
}
}
而且,这将是如何使用它:
Future<Void> f = executorService.submit(new MyRunnable());
f.get(2, TimeUnit.SECONDS);
关于问题中的终止属性,示例Runnable不是一个好的,因为它does not provide an interruptible task。例如,如果添加了sleep
操作:
public class MyRunnable implements Runnable {
private int count = 0;
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(count++);
try {
Thread.sleep(0, 1);
} catch (InterruptedException x) {
return;
}
}
}
}