How to correctly and gracefully terminate a running thread in Java

Source: Internet
Author: User
Tags volatile

There are three main ways to terminate threads in Java:

1, using the Stop () method, has been deprecated. The reason for this is that stop () is terminated immediately, causing some data to be terminated as part of the processing, and the user does not know which data is processed, which is not processed, produces incomplete "disability" data, does not conform to integrity, and is discarded. So, forget it!

2, the use of volatile logo bit

Look at a simple example:

First, implement a runnable interface in which you define the volatile flag bit and use the flag-bit control program in the Run () method.

public class Myrunnable implements Runnable {

	//define exit flag, True will always execute, false will exit loop
	//use volatile to ensure visibility, one to modify the flag, Always go to main memory to read the new value instead of using the cached public
	volatile Boolean flag = true;

	public void Run () {
		System.out.println ("First" + Thread.CurrentThread (). GetName () + "thread Creation");
		
		try {
			thread.sleep (1000L);
		} catch (Interruptedexception e) {
			e.printstacktrace ();
		}
		
		Exit flag takes effect while
		(flag) {
		}
		System.out.println ("First" + Thread.CurrentThread (). GetName () + "thread termination");
}
Then, create the thread in the main () method and, when appropriate, modify the flag bit to terminate the running thread.

public class Treadtest {public
	static void Main (string[] arg) throws interruptedexception {
		myrunnable runnable = New Myrunnable ();
		
		Create 3 threads
		for (int i = 1; I <= 3; i++) {
			thread thread = new Thread (runnable, i + "");
			Thread.Start ();
		}
		Thread dormancy
		thread.sleep (2000L);
		System.out.println ("——————————————————————————");
		Modify exit flag to cause thread to terminate
		Runnable.flag = false;	
	}
Finally, run the results as follows:


3, using the interrupt () interrupt, note that using the interrupt () method to interrupt the running of the thread will only modify the interrupt state bit, can be judged by isinterrupted (). If you interrupt a thread in blocking by using the interrupt () method, you throw a interruptedexception exception, you can catch the exception through a catch, and then terminate the thread after processing. In some cases, we cannot judge the state of the thread, so we must consider it carefully when using the interrupt () method.

Look at a simple example (interrupt running threads):

The public class MyRunnable2 implements runnable{the public
	
	Void Run () {
		System.out.println (thread.currentthread). GetName () + "thread Creation");
		try {
			thread.sleep (1000L);
		} catch (Interruptedexception e) {
			e.printstacktrace ();
		}
		When a thread at run time is interrupted, only the interrupt token is modified, and the exception while
		(Thread.CurrentThread (). isinterrupted ()) {
			
		}
		System.out.println () is not thrown. Thread.CurrentThread (). GetName () + "thread Interrupted");

public class Treadtest {public
	static void Main (string[] arg) throws interruptedexception {
		Runnable Runnable = New MyRunnable2 ();
		
		Create 3 threads thread
		thread1 = new Thread (runnable, "1");
		Thread thread2 = new Thread (runnable, "2");
		Thread thread3 = new Thread (runnable, "3");
		Thread1.start ();
		Thread2.start ();
		Thread3.start ();
		
		Thread dormancy
		thread.sleep (2000L);
		
		Modify the exit flag so that the thread terminates
		thread1.interrupt ();
		Thread2.interrupt ();
		Thread3.interrupt ();
	}
Execution results:







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.