1. setDeamon
Set the thread to a function running in the background
Public class SetDaemon {public static void main (String [] args) throws InterruptedException {Thread tt = new Thread (new ThreadTest (); tt. setDaemon (true); // set the program to run tt in the background. start (); Thread. sleep (3) ;}} class ThreadTest implements Runnable {public void run () {while (true) {System. out. println (Thread. currentThread (). getName () + "is running... ");}}}
It can be seen that the thread running in the background of the parent thread automatically ends. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Margin = "brush: java;"> public class SetDaemon {public static void main (String [] args) throws InterruptedException {Thread tt = new Thread (new ThreadTest ()); tt. start (); for (int I = 0; I <10; I ++) {if (I = 5) {tt. join ();} System. out. println (Thread. currentThread (). getName () + I + "is running... ") ;}} class ThreadTest implements Runnable {public void run () {for (int I = 0; I <5; I ++) {System. out. println (Thread. currentThread (). getName () + I + "is running... ");}}}
3. interrupt thread
public class SetDaemon{public static void main(String[] args) throws InterruptedException{Thread tt=new Thread(new ThreadTest());tt.start();Thread.sleep(2000);System.out.println("The subthread is interupted in the main thread.");tt.interrupt();tt.join();System.out.println("The main thread is over.");}}class ThreadTest implements Runnable{public void run(){try{System.out.println("The subthread is sleeping...");Thread.sleep(200000);}catch(Exception e){e.printStackTrace();System.out.println("The subthread is interupted.");return;}System.out.println("The subthread is over.");}}
Note: The thread interruption is not the same as the hardware interruption. The hardware interruption is... (Don't talk about it.) Here, the interruption can be understood as the thread state being set to the interrupt state (that is, a flag is suspended to tell other threads that 'Brother is in the interrupt State ', some operations are prohibited. In this case, executing some functions triggers an exception and the interrupted thread enters the exception handling code segment.
Read the following code carefully:
public class SetDaemon{public static void main(String[] args) throws InterruptedException{Thread tt=new Thread(new ThreadTest());tt.start();Thread.sleep(5);System.out.println("The subthread is interupted in the main thread.");tt.interrupt();tt.join();System.out.println("The main thread is over.");}}class ThreadTest implements Runnable{public void run(){try{while(true){System.out.println(Thread.currentThread().getName()+" is running...");Thread.sleep(1);}}catch(Exception e){e.printStackTrace();System.out.println("The subthread is interupted.");return;}//System.out.println("The subthread is over.");}}
You can use isInterupt () to check whether the thread is interrupted.