"Java concurrent programming combat," the seventh chapter to cancel and close reading Notes __java Foundation

Source: Internet
Author: User


Java does not provide any mechanism to safely terminate threads (preemptive method), although methods such as Thread.stop and suspend provide such mechanisms, but they should be avoided because of some serious flaws. But it provides an interrupt interruption mechanism, a collaboration mechanism that enables one thread to terminate the current work of another thread.
I. Cancellation of tasks reason for canceling the operation:
. User request Cancellation
. Operations with TIME constraints
. Application Events
. Error
. Shut down
four ways to end a task:1. Run method execution end 2. Use the request close tag (for example, Boolean switch) 3. Use interrupt mechanism 4. Using the future Exit method

2. Using the request close tag when executing to and satisfying the condition is using return to exit the Run method variable requires volatile to ensure the visibility of the variable in a multithreaded environment. -Examples to fill, without execution to judge conditions will not exit, so not immediately exit the method.
3. The advantage of using the interrupt mechanism is that it is relatively faster than the "request close tag", but it is also not an immediate shutdown of the thread.      Break thread in void interrupt (). Boolean interrupted () tests when the thread has been interrupted.
The Boolean isinterrupted () tests whether the thread has been interrupted. Interruptedexception exception
The program should respond appropriately to thread interrupts.
  1
thread thread = new Thread ("Interrupt test") {public
	void run () {A for
		(;;) {
			doxxx ();
			if (thread.interrupted ()) {Break;}}}}
;
Thread.Start ();



2
thread thread = new Thread ("Interrupt test") {public
	void run () {A for
		(;;) {
			try {
				doxxx ();
			} catch (Interruptedexception e) {break
				;
			} catch (Exception e) {
				// Handle Exception
			}}}
;
Thread.Start ();  3 public
void foo () throws Interruptedexception {
	if (thread.interrupted ()) {
		throw new Interruptedexception ();
	}



4. Use future Exit method
Boolean Cancel (Boolean mayinterruptifrunning)
An attempt was made to cancel execution of this task.
Boolean iscancelled ()
Returns true if the task is canceled before it is properly completed.

*. Handle an interruptible block *. The cancellation of the package fee standard by using newtaskfor

second, stop the thread based serviceThe previous task was canceled, mainly involving how to close a single thread and all by creating an object for a single thread to close the operation, but what if the thread was not created by the object itself but by the thread pool.       1. Use the object of the thread to close-Currently, even if you do not create a thread in the object and are created by the thread pool, the object can still shut down the thread, and you must trust the programmer's ability to destroy, but use the 2nd way to better conform to the encapsulation principle. 2. Use thread pooling for unified management-if it is created using Executorservice, it is turned off.
2. Use thread pooling for unified management (turn off executorservice) void shutdown ()
Initiates a sequential shutdown, performs a previously committed task, but does not accept new tasks.       If it is already closed, the call has no other effect. --Safe shutdown mode.
List<runnable> Shutdownnow ()
An attempt was made to stop all active tasks, suspend processing of waiting tasks, and return a list of tasks waiting to be executed.
There is no guarantee that you can stop the activities you are working on, but try to do the work.            For example, by Thread.Interrupt () to cancel a typical implementation, any task that cannot respond to an interrupt may never be terminated. --The limitations of the Shutdownnow method, the forced shutdown mode. Boolean IsShutDown ()
Boolean IsShutDown () returns True if this executor is closed.
3. "Poison pill" objects can be used only if the number of producers and consumers is known.
Third, handling abnormal thread termination Thread.uncaughtexceptionhandler Global catch exception handling, usually in the application for exception statistics, after collecting these statistics can be used for abnormal repair.
Four, JVM shutdown1. Close Hook Runtime.getruntime (). Addshutdownhook (New Thread ());
void Addshutdownhook (Thread hook)
Register a new virtual machine to close the hook.
2. The daemon thread wants to create a thread to perform some ancillary work, but does not want this thread to hinder the JVM from shutting down and can use a daemon.
3. finalizers Avoid using finalizers finalize




v. reference materials:"Program should respond appropriately to thread interrupts" excerpt from the Win Shaojin-Java Concurrent Programming tutorial



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.