I'm new to Java concurrent package and want to try ExecutorService to control the execution time of a thread.
So for a keep running thread MyThread, I want to use ExecutorService and Future class to stop it after 2 seconds.
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();
}
}
However, the thread is still keep printing numbers after 2 seconds. How can I control the thread without changing MyThread class itself?