java - Use ExecutorService to control thread execution time -
i'm new java concurrent package , want try executorservice control execution time of thread.
so keep running thread mythread, want use executorservice , future class stop 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, thread still keep printing numbers after 2 seconds. how can control thread without changing mythread class itself?
the main purpose of using executorservice
hide how threads created, reused , in general managed programmer.
instead of creating mythread
, need implement runnable
:
public class myrunnable implements runnable { private int count = 0; public void run() { while (true) { system.out.println(count++); } } }
and, how use it:
future<void> f = executorservice.submit(new myrunnable()); f.get(2, timeunit.seconds);
regarding termination property in question, example runnable not one, because does not provide interruptible task. example, if sleep
operation added:
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; } } } }
Comments
Post a Comment