java - Why put the main thread to sleep before cancelling a timer task? -
in this example author puts main thread running timer task sleep before cancelling timer task this:
system.out.println("timertask started"); //cancel after sometime try { thread.sleep(120000); } catch (interruptedexception e) { e.printstacktrace(); } timer.cancel(); system.out.println("timertask cancelled"); try { thread.sleep(30000); } catch (interruptedexception e) { e.printstacktrace(); } }
after cancelling author puts sleep 30 seconds. curious why done? show timer still run though main thread sleeping , additional 30 seconds added allow timer chance cancel itself? there way tell timer cancel after 120 seconds without putting main thread sleep?
follow up
great answer - follow question make sure understand correctly- if thread non daemon , cancel first task after 2 minutes using timer schedule task showed, stop main thread (as tasks scheduled cancelled)?
the code demonstrative. sleeps there show difference before , after cancelling task. waits 2 minutes show timer doing work every 10 seconds, cancels task , waits 30 seconds can see no longer doing work.
also there way tell timer cancel after 120 seconds without putting main thread sleep?
one option scheduling second timer task run after 120 seconds, runnable code cancels first task.
timer timer = new timer(false); timertask firsttask = new timertask() { @override public void run() { system.out.println("hitme"); } }; timer.scheduleatfixedrate(firsttask, 5000, 5000); timer.schedule(new timertask() { @override public void run() { firsttask.cancel(); } },45000);
you need careful though, because timer
, other scheduled executors run daemon threads. if main method finishes , threads left daemon threads, jvm terminate regardless of whether there pending tasks.
in case of example, author passing true
constructor of timer
, means will run daemon. if left unchanged, , sleeps removed, jvm exit remaining thread daemon timer thread. flipside of making non-daemon jvm never exit unless other thread cancels timer
.
edit
i realized timertask
not lambda-compatible type, method reference doesn't work there.
Comments
Post a Comment