JAVA learning notes (40)-daemon thread and interrupt thread, java learning notes
Daemon thread
/** Daemon threads, that is, Daemon threads * generally run in the background to provide services for other threads, cannot exist separately */public class Test08 {public static void main (String [] args) {MyThread8 t1 = new MyThread8 ("daemon thread"); System. out. println ("Is it a daemon thread? "+ T1.isDaemon (); t1.setDaemon (true); System. out. println (" Is it a daemon thread? "+ T1.isDaemon (); t1.start (); new MyThread8 (" rubbish "); for (int I = 1; I <= 100; I ++) {System. out. println (Thread. currentThread (). getName () + "*****" + I) ;}} class MyThread8 extends Thread {public MyThread8 (String name) {super (name); setDaemon (true ); start () ;}@ Override public void run () {while (true) {System. out. println (Thread. currentThread (). getName () + "garbage collection in progress! ");}}}
Interrupt thread
/** Interrupt () interrupt thread */public class Test09 {public static void main (String [] args) {MyThread9 mt = new MyThread9 (); thread thread = new Thread (mt, "first"); thread. start (); for (int I = 1; I <= 20; I ++) {System. out. println (Thread. currentThread (). getName () + "***");} try {Thread. sleep (3000); // The main thread goes to bed for 3 seconds} catch (InterruptedException e) {e. printStackTrace ();} // sleep thread of thread 1 interrupted. interrupt () ;}} class MyThre Ad9 implements Runnable {int num = 1; @ Override public void run () {while (true) {if (num = 10) {try {System. out. println (Thread. currentThread (). getName () + "the Thread is about to fall asleep for 10 seconds"); Thread. sleep (10000);} catch (InterruptedException e) {System. out. println ("I will wake up .... "); // E. printStackTrace () ;}} System. out. println (Thread. currentThread (). getName () + "***" + num ++ );}}}