Java Multithread-Thread-Interrupt

I. overview

A Java program executed by multiple threads will only end when all of its threads are executed (more specifically, when all non-daemon threads end or a thread calls the System.exit() method).

Interrupt A thread means that it stops everything it's doing before it finishes its task and effectively terminates its current operation. Whether a thread dies, waits for a new task, or continues to run until the next step depends on the program. Although it may seem simple at first sight, you have to do some early warning to achieve the desired results.

Two, implementation

Case 1: The best and most recommended way to interrupt a thread is to use shared variables to signal that the thread must stop running tasks. Threads must periodically check this variable (especially during redundant operations) and then terminate tasks in an orderly manner.

public class ThreadInterruptTest extends Thread {

	  volatile boolean stop = false;

	  public static void main( String args[] ) throws Exception {

		   ThreadInterruptTest thread = new ThreadInterruptTest();
		   System.out.println( "Starting thread..." );
		   thread.start();
		   
		   Thread.sleep(3000);
		   System.out.println( "Asking thread to stop..." );
		   thread.stop = true;
		   Thread.sleep(2000);
		   System.out.println( "Stopping application..." );
	  }

	  public void run() {		  
	    while ( !stop ) {
	      System.out.println( "Thread is running..." );
	      long time = System.currentTimeMillis();
	      while ( (System.currentTimeMillis()-time < 1000) && (!stop) ) {
             
	      }
	    }
	    System.out.println( "Thread exiting under request..." );
	  }	
}
//console result: - > after interruption, exit sequentially
Starting thread...
Thread is running...
Thread is running...
Thread is running...
Thread is running...
Asking thread to stop...
Thread exiting under request...
Stopping application...

Case 2: Use of interrupt()

public class Consumer implements Runnable{
	
	public void run() {
	    try{  
            System.out.println("in run() - about to sleep for 20 seconds");  
            Thread.sleep(20000);  
            System.out.println("in run() - woke up");  
        }catch(InterruptedException e){  
            System.out.println("in run() - interrupted while sleeping");  
            //After handling the interrupt exception, return to the run () method population.  
            //If there is no return, the thread will not actually be interrupted, and it will continue to print the following information  
            return;    
        }  
        System.out.println("in run() - leaving normally");  
	}
}
public class TestInterrupt {

	public static void main(String[] args) {
		Consumer si = new Consumer();  
        Thread t = new Thread(si);  
        t.start();  
        //The main thread hibernates for 2 seconds to ensure that the thread just started has an opportunity to execute for some time.  
        try {  
            Thread.sleep(2000);   
        }catch(InterruptedException e){  
            e.printStackTrace();  
        }  
        System.out.println("in main() - interrupting other thread");  
        //Interrupt thread t  
        t.interrupt();  
        System.out.println("in main() - leaving");  
	}
}
//console results:
in run() - about to sleep for 20 seconds
in main() - interrupting other thread
in main() - leaving
in run() - interrupted while sleeping
in run() - leaving normally

Description: After the main thread starts a new thread, it hibernates itself for 2 seconds, allowing the new thread to get running time. After the new thread prints the information "about to sleep for 20 seconds" and then sleeps for 20 seconds, but after about 2 seconds, the main thread notifies the new thread of interruption, then the new thread's 20 seconds sleep will be interrupted, thus throwing an InterruptException exception, executing jumps to the catch block, printing out the "interrupted while sleeping" information, and returning immediately from the run () method, and then The "leave normal" message behind the catch block is not printed out.

Note: Due to uncertain thread planning, the last two rows of the above results may be in reverse order, depending on which of the main thread and the new thread will die first. But the order of the first two lines of information must be as shown in the figure above. In addition, if the return statement in the catch block is commented out, the thread will continue to execute without interruption after throwing an exception, thus printing out the "leaving normal" message.

Case 3: Use of interrupt()

public class TestRunnable implements Runnable{

	public void run() {
		boolean isRunning = true;
		while(isRunning){
			System.out.println("Thread is running...");
			long start = System.currentTimeMillis();
			if(System.currentTimeMillis() - start < 1000){
				
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
                isRunning = false; // If removed, run is equivalent to not interrupting, then proceeding 
                System.out.println("Run Thread is end..");
			}
		}
	}
}
public class ThreadDemo {

	public static void main(String[] args) {
		TestRunnable testRunnable = new TestRunnable();
		Thread thread = new Thread(testRunnable);
		thread.start();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		thread.interrupt();
	    System.out.println("main Thread is end..");	
	}
}

/** console Result:
 *Thread is running...
 *main Thread is end..
 *Run Thread is end..
 */

Keywords: Java

Added by 9902468 on Sat, 01 Jun 2019 01:10:03 +0300