Java advanced multithreaded programming (1) -- thread stop
Multithreading is an advantage of Java. Java allows programmers to easily develop multithreaded programs. For better performance.
Regarding the concept of multithreading and general multi-threaded programming, such as how and why the runnable interface is implemented, and why stop () is deprecated, for details, refer to the multi-threaded programming basics of matrix or Sun's Java documentation.
For multithreaded programming, there are several points to mention:
1. Since stop () is not recommended, how do we stop a thread? Kill directly? Here, I will summarize a more general and stable method:
Class threadtest extend thread {
// Skip some code ..
Boolean runflag = true;
Public synchronized void stopthread ()
{
Runflag = false;
}
Public synchronized Boolean getrunflag ()
{
Return runflag;
}
Public void run (){
Runflag = true;
Try {
While (getrunflag ()){
Code1;
Code2;
// Put your code here
}
}
}
Catch (ioexception e ){
E. printstacktrace ();
}
System. Out. println (this. getclass (). getname () + "STOPPED ");
}
// Skip some code ..
}
In this way, you only need to call stopthread () whenever you need to stop the thread.
Note the following two points:
1) We used a synchronization method getrunflag () to get the current state. Why is this method used instead of using while (runflag) directly?
This is because there is a public Object Storage zone in the Java multi-threaded model, but each object has its own private backup. When a thread changes its status, JVM does not guarantee that the variables changed by this thread are updated to the state of the public Object Storage zone in real time, which may (unlikely) cause problems.
Therefore, we recommend that you have good design habits and use the synchronization method to obtain the current runflag value.
2) Another point is that if network congestion occurs (in the while loop), even if the runflag status changes to false, due to program blocking, the thread will never be stopped using this method.
For example, in the above program, if code1 is a network program and code1 is blocked, blocking means that the request is not obtained.
Resource, waiting for an indefinite period. At this time, the change of the runflag status does not affect the while loop, and the thread will not be stopped.
I have participated in several Java programs that involve obtaining network resources and often encounter thread problems caused by network congestion.
If your program may involve network blocking, or some message blocking may occur. Do not stop the thread in this way. For details, refer to the author's article: advanced multithreading programming (2)-monitoring and timeout issues in multithreading.