Packagecom.example; Public classApp { Public Static voidMain (string[] args) {Dodaemon D1=NewDodaemon (); Dorunnable D2=NewDorunnable ("Sinny"); Thread T1=NewThread (D1); Thread T2=NewThread (D2); //set as a background thread,T1.setdaemon (true); T1.start (); T2.start ();//after the user thread finishes, the JVM exits automatically, no longer waiting for background processes }}
Packagecom.example; Public classDodaemonImplementsrunnable{@Override Public voidrun () { for(inti = 0; I < 300; i++) { Try{Thread.Sleep (5); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Hello__deamon"); } }}
Packagecom.example; Public classDorunnableImplementsRunnable {PrivateString name; Publicdorunnable (String name) { This. Name =name; } @Override Public voidrun () { for(inti = 0; I < 3; i++) { Try{Thread.Sleep (5); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Hello__" + This. Name); } }}
Java Multithreading (daemon)