Thread BASICS (Part 2) Java thread defects and side effects Solutions
Source: Internet
Author: User
Thread BASICS (Part 2) Java thread defects and side effects solutions-Linux general technology-Linux programming and kernel information. The following is a detailed description. Al Saganich
<-- In the second part of thread basics, we will learn about the defects and side effects of using Java threads, and how to modify the thread running mechanism in sun jdk 1.2 -->
In the previous article "thread basics of Java 101", we introduced the concept of thread and how to use it. This month, we will go to more advanced topics, including thread defects and side effects, and how to improve the thread running mechanism in sun jdk 1.2.
Synchronize (synchronous)
Let's recall what we mentioned in the previous article: The thread allows two or more processes to run simultaneously. In fact, these threads can also share objects and data. In this case, you need to know that different threads cannot access the same data at the same time, because at the beginning of Java design, the thread concept is adopted. the Java language defines a special keyword synchronize (synchronous), which can be applied to the code block. The code block also includes the entry method, the purpose of this keyword is to prevent multiple threads from executing code within the same code block at the same time.
Define a synchronization method in the following format:
[Public | private] synchronized {type}
Methodname (...)
A simple example of applying the synchronization keyword to a method:
Public class someClass {
Public void aMethod (){
// Some code
Synchronized (this ){
// Synchronized code block
}
// More code.
}
}
The synchronization keyword ensures that only one thread can execute the code segment at a time, and any other thread that needs to use the code segment will be blocked until the first thread finishes executing the code segment.
Deadlock and hunger
Definition of hunger-because other concurrent Activation Processes occupy the required resources for a long time, it is not allowed to be activated within the time predicted by the passengers in an asynchronous process.
The two most common defects of threads are deadlock and hunger. A deadlock occurs when one or more processes work collaboratively and interfere with each other in a given task, causing one or more processes to wait forever. Similarly, when a process occupies resources permanently, so that other processes do not obtain the resource, hunger may occur.
First, let's take a look at the deadlock issue. Consider a simple example. If you get money from an ATM, but you see the following information: "Is there any cash? Please try again later ." You need money, so you will wait for a while and try again, but you will see the same information. At the same time, behind you, an armored car is waiting to put the money in the ATM, but the armored car cannot reach the ATM, because your car is blocked. And you have to get the money to leave the original place. In this case, a deadlock occurs.
In the case of hunger, the system is not in a deadlock, because one process is still being processed, but other processes will never be executed. In what circumstances will hunger occur and there are no predefined rules. Once one of the following four situations occurs, the deadlock will occur.
Mutual Exclusion: a thread or process always occupies a shared resource. For example, a thread or process occupies an exclusive resource.
Loop wait: process A waits for process B, while process C waits for Process C, and process C waits for process.
Partial allocation: resources are partially allocated. For example, process A and process B both need to access A file and use A printer. process A obtains the file resources and process B obtains the printer resources, however, the two processes cannot obtain all resources.
Lack of priority: A process accesses a resource but never releases the resource, even if the process is in a blocking status.
If none of the above four situations occurs, the system will not experience deadlocks. Let's take a look at the file/printer example. When one of the processes determines that it cannot get the second resource it needs, it releases the first resource it has obtained, in the second tutorial, you can get two resources and run them.
Advanced thread usage
So far, we have talked about the basic knowledge of creating and managing threads. What you need to do is to start a thread and run it. Your application may want to wait for the execution of a thread to complete, or you may want to send a message to the thread, or just want the thread to sleep for a while before processing. The thread class provides four API calls to operate on threads.
Join
If an application needs to execute a lot of time, for example, a long computing task, you can design the task as a thread. However, if there is another thread that needs to calculate the results, how can we let that thread know the results after the calculation results come out? One way to solve this problem is to keep the second thread checking the status of some variables until the status of these variables changes. This method is often used in UNIX-style servers. Java provides a simpler mechanism, that is, the join method in the Thread class.
The join method causes a thread to wait for the end of another thread. For example, a GUI (or other threads) uses the join method to wait for a subthread to finish executing:
CompleteCalcThread t = new
CompleteCalcThread ();
T. start ();
//
// Do other things for a while
// Wait
T. join ();
// Use the calculation result...
You can see that the subthread uses the join method to wait for the sub-thread to complete execution. Join has three formats:
Void join (): Wait until the thread execution is complete.
Void join (long timeout): Wait for a certain period of time for the thread to complete.
Void join (long milliseconds, int nanoseconds): Wait for a certain period of time (in milliseconds + nanoseconds) for the thread to complete.
When the thread API isAlive is associated with the join operation, it is very useful. A thread is in the isAlive status at a certain time before start (the run method has been started at this time.
For programmers who write threads, there are two other useful thread APIs, namely wait and notify. With these two APIs, We can precisely control the thread execution process. Consider a simple example. There is a producer thread and consumer thread. To make the application more efficient, we do not plan to use the query wait method. When a consumer can consume objects, the consumer needs to know the information.
We can illustrate this example as follows: the producer thread is constantly running and the project is put into the list. The add method of the List is protected by the synchronize keyword, when an object is added to the list, the producer can notify the consumer that an object has been added and the consumer can consume the object. For the pseudocode of the run method of each object, see Table.
Table A: pseudocode of advanced thread Methods
Class ProdCons {
Class List {
Public synchronized boolean add (Object o)
{...}
Public synchronized boleanremove (Object o)
{...}
}
List data = new List ();
ProdThread producer = null;
ConsThread consumer = null;
ProdCons (){
Producer = new ProdThread (this );
Consumer = new ConsThread (this );
Producer. start ();
Consumer. start ();
}
}
For consumer and producer classes, see table B and Table C.
Table B: Class ConsThread
Class ConsThread extends Thread {
ProdCons parent;
ConsThread (ProdCons parent ){
This. parent = parent;
}
Public synchronized void canConsume (){
Notify ();
}
Public void run (){
Boolean consumed;
Do {
Synchronized (this ){
Try {wait ();}
Catch (Exception e ){;}
}
Do {
String str = (String) parent. list. remove ();
If (null = str ){
Consumed = false;
Break;
}
Consumed = true;
System. out. println ("Consumer
=> Consumed "+ str );
}
While (true );
}
While (consumed );
}
}
Table C: Class ProdThread
Class ProdThread extends Thread {
ProdCons parent;
ProdThread (ProdCons parent ){
This. parent = parent;
}
Public void run (){
For (int I = 0; I <10; I ++ ){
String str = new String ("ImAString" + I );
System. out. println ("Producer produced" + str );
Parent. list. add (str );
Parent. consumer. canConsume ();
}
Parent. consumer. canConsume ();
}
}
Note: both policy and wait APIs must be in the synchronized method or code block!
Thread and Sun JDK 1.2
Threads provide a very valuable service and greatly enhance the functions of Java programming language. However, the current thread implementation does have some problems. The existence of these problems caused criticism by the stop, suspend, and resume methods of threads in Sun JDK 1.2.
If we return to the producer/consumer example above, we can better understand this problem. First, let's look at the deadlock. When running an applet, when two threads run normally, the problem occurs. If the producer is adding a project to the list, the worst case is that the consumer thread is blocked. Assuming that the applet is creating an object and is suddenly suspended, other applets cannot update the data. Although there are not many such opportunities, they do exist and sometimes cause problems.
The second thread issue is related to inconsistency. Let's take a look at the producer/consumer example. It is hard to imagine that if the producer thread is aborted during project addition, the list status may be inconsistent. If we fully check the number of existing Java applets, it is not difficult to find the problem.
The simplest way to deal with this inconsistency is to derive a new Thread class which has the following functions: A method call can change its status. Table D defines such a class. The MyThread class can be suspended and re-executed without worrying that the resources of the MyThread class will crash. The changeState method in the MyThread class is used to imply that the thread should be paused, stopped, or re-executed, unlike the previous thread to be stopped or paused. A request can be sent to the thread, requiring the thread to process the request at the appropriate time, rather than forcibly processing the request, so there is no need to send a Stop command to the thread.
Table D: Class MyThread
Public class MyThread extends Thread {
// States the thread can be in.
Static final int STATE_RUNNING = 0;
Static final int STATE_STOP = 1;
Static final int STATE_SUSPEND = 2;
Private int currentState = STATE_RUNNING;
// The public method changeState allows
// Another process to poke at that hread
// And tell it to do something when it
// Next gets a chance.
Public final synchronized void
ChangeState (int newState ){
CurrentState = newState;
If (STATE_RUNNING = currentState)
Notify ();
// Must have been susponded.
}
Private synchronized boolean currentState (){
// If we where asked to suspend,
// Just hang out until we are
// Asked to either run or stop.
While (STATE_SUSPEND = currentState ){
Try {wait ();}
Catch (Exception e ){};
}
If (STATE_STOP = currentState)
Return false;
Else
Return true;
}
Public void run (){
Do {
If (currentState () = false)
Return; // Done
// Perform some work
} While (true );
}
}
Users of the MyThread class can reload the run method. However, users need to check whether there are other types of request threads that change the status. Changes made to the thread running mechanism in JDK 1.2 are the crux of the problem. Are there any inconsistencies in the thread running and whether to discard the occupied resources after the thread is closed, whether the thread is running normally requires the developer to complete the work.
Conclusion
Threads are powerful and complex to use. Every Java developer can use threads in many applications. In this article, we checked some side effects of the thread and some advanced usage of the thread. With the launch of Sun JDK 1.2, developers will be forced to take into account the effect of the threads they write on the system and other processes. In the end, a correct understanding of threads and related knowledge will help smart developers design more robust applications.
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