java - Daemon thread not working as expected -
package main.components; import java.io.serializable; import java.util.scanner; import java.util.concurrent.timeunit; public class mainsnoozerx implements runnable, serializable { private static final long serialversionuid = 1l; private static int min = 0; static thread mnz = new thread(new mainsnoozerx()); private long convertedtomilisec = 0l; private scanner scn = new scanner(system.in); @override public void run() { // todo auto-generated method stub try{ do{ system.out.println("enter minutes snooze.."); min = scn.nextint(); }while(min<0); convertedtomilisec = timeunit.minutes.tomillis(min); try { thread.sleep(convertedtomilisec); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println("alarm now!!!"); }catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } } public static void main(string[] args) { // todo auto-generated method stub mnz.setdaemon(true); mnz.start(); } }
can tell me doing wrong/missing? program terminates when run without printing syso once. expect code run endlessly being daemon thread , user sets mins once , snooze goes on forever...
you fired thread without ever tell java want work done back. need add mnz.join()
after start ;)
with fix, thread run 1 time sure. if decide put run() code inside of while loop , change loop, got behaviour want.
like this
@override public void run() { while (true) { // todo auto-generated method stub try { while (min == 0) { system.out.println("enter minutes snooze.."); min = scn.nextint(); } convertedtomilisec = timeunit.minutes.tomillis(min); try { thread.sleep(convertedtomilisec); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println("alarm now!!!"); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } } } public static void main(string[] args) throws interruptedexception { // todo auto-generated method stub mnz.setdaemon(true); mnz.start(); mnz.join(); }
Comments
Post a Comment