Fully Understand Java multithreading-Inter-thread communication (2)

Source: Internet
Author: User
Thoroughly understand Java's multithreading-Inter-thread communication (2)-Linux general technology-Linux programming and kernel information. The following is a detailed description. 2.4 differences between sleep () and yield ()
1) sleep () causes the current thread to enter the stuck state, so the thread executing sleep () will certainly not be executed within the specified time; yield () it only enables the current thread to return to the executable State. Therefore, the thread that executes yield () may be executed immediately after it enters the executable state.
2) sleep () can lead to execution of low-priority threads. Of course, it can also lead to execution of threads with the same priority and higher priority; yield () only threads with the same priority can have execution opportunities.
Example 15:
Class TestThreadMethod extends Thread {
Public static int shareVar = 0;
Public TestThreadMethod (String name ){
Super (name );
}
Public void run (){
For (int I = 0; I <4; I ++ ){
System. out. print (Thread. currentThread (). getName ());
System. out. println (":" + I );
// Thread. yield (); (1)
/* (2 )*/
Try {
Thread. sleep (3000 );
}
Catch (InterruptedException e ){
System. out. println ("Interrupted ");
}

}
}
}
Public class TestThread {
Public static void main (String [] args ){
TestThreadMethod t1 = new TestThreadMethod ("t1 ");
TestThreadMethod t2 = new TestThreadMethod ("t2 ");
T1.setPriority (Thread. MAX_PRIORITY );
T2.setPriority (Thread. MIN_PRIORITY );
T1.start ();
T2.start ();
}
}
The running result is:
T1: 0
T1: 1
T2: 0
T1: 2
T2: 1
T1: 3
T2: 2
T2: 3
As can be seen from the results, sleep () can be used to give lower-priority threads the opportunity to execute. Comment out code (2) and remove the comments of code (1). The result is:
T1: 0
T1: 1
T1: 2
T1: 3
T2: 0
T2: 1
T2: 2
T2: 3
It can be seen that when yield () is called, threads with different priorities will never get execution opportunities.
2.5 join ()
After the thread that calls join () is executed, other threads can be executed. In a certain sense, it can implement the synchronization function.
Example 16:
Class TestThreadMethod extends Thread {
Public static int shareVar = 0;
Public TestThreadMethod (String name ){
Super (name );
}
Public void run (){
For (int I = 0; I <4; I ++ ){
System. out. println ("" + I );
Try {
Thread. sleep (3000 );
}
Catch (InterruptedException e ){
System. out. println ("Interrupted ");
}
}
}
}
Public class TestThread {
Public static void main (String [] args ){
TestThreadMethod t1 = new TestThreadMethod ("t1 ");
T1.start ();
Try {
T1.join ();
}
Catch (InterruptedException e ){}
T1.start ();
}
}
The running result is:
0
1
2
3
0
1
2
3


3. common thread functions in class Object
The wait (), Policy (), and policyall () functions are provided by the java. lang. Object class to coordinate multiple threads to access Shared data.
3.1 wait (), notify (), and policyall ()
1) The wait () function has two forms: the first form accepts a millisecond value, used to suspend the thread within a specified period of time, so that the thread enters the stuck state. The second form is without parameters, which means that waite () will continue to stagnate before notify () or notifyAll.
2) When running notify () on an object, it will remove any thread from the thread wait pool and put it in the lock sign waiting pool; when running yyall () on an object () all threads of the object will be removed from the thread wait pool, and they will be placed in the lock sign wait pool.
3) When wait () is called, the thread will release the lock mark it occupies, so that other synchronized data in the thread's object can be used by other threads.
Example 17:
Next, we will modify the example in example 11.
Class TestThreadMethod extends Thread {
Public static int shareVar = 0;
Public TestThreadMethod (String name ){
Super (name );
}
Public synchronized void run (){
If (shareVar = 0 ){
For (int I = 0; I <10; I ++ ){
ShareVar ++;
If (shareVar = 5 ){
Try {
This. wait (); // (4)
}
Catch (InterruptedException e ){}
}
}
}
If (shareVar! = 0 ){
System. out. print (Thread. currentThread (). getName ());
System. out. println ("shareVar =" + shareVar );
This. Y (); // (5)
}
}
}
Public class TestThread {
Public static void main (String [] args ){
TestThreadMethod t1 = new TestThreadMethod ("t1 ");
TestThreadMethod t2 = new TestThreadMethod ("t2 ");
T1.start (); // (1)
// T1.start (); (2)
T2.start (); // (3)
}
}
The running result is:
T2 shareVar = 5
Because t1 and t2 are two different objects, thread t2 call code (5) cannot evoke thread t1. If the comments of code (2) are removed and the code (3) is commented out, the result is:
T1 shareVar = 5
T1 shareVar = 10
This is because when the thread of code (1) is executed to code (4), it enters the stuck state and releases the lock state of the object. Then, the Code (2) thread executes run (). Because the shareVar value is 5 at this time, execute the print statement and call code (5) to make code (1) the thread enters the executable state, and the thread of code (2) ends. When the code (1) thread re-executes, it then executes the for () loop until shareVar = 10, and then prints the shareVar.
3.2 wait (), notify (), and synchronized
Waite () and Y () are called in the synchronized function or synchronized block because they operate on the object's "lock flag. If the call is performed in the non-synchronized function or the non-synchronized block, the IllegalMonitorStateException exception may occur at runtime although the compilation is successful.
Example 18:
Class TestThreadMethod extends Thread {
Public int shareVar = 0;
Public TestThreadMethod (String name ){
Super (name );
New Notifier (this );
}
Public synchronized void run (){
If (shareVar = 0 ){
For (int I = 0; I <5; I ++ ){
ShareVar ++;
System. out. println ("I =" + shareVar );
Try {
System. out. println ("wait ......");
This. wait ();
}
Catch (InterruptedException e ){}
}
}
}
}
Class Notifier extends Thread {
Private TestThreadMethod ttm;
Notifier (TestThreadMethod t ){
Ttm = t;
Start ();
}
Public void run (){
While (true ){
Try {
Sleep (2000 );
}
Catch (InterruptedException e ){}
/* 1 the method to synchronize is not the current object */
Synchronized (ttm ){
System. out. println ("policy ......");
Ttm. Y ();
}
}
}
}
Public class TestThread {
Public static void main (String [] args ){
TestThreadMethod t1 = new TestThreadMethod ("t1 ");
T1.start ();
}
}
The running result is:
I = 1
Wait ......
Using y ......
I = 2
Wait ......
Using y ......
I = 3
Wait ......
Using y ......
I = 4
Wait ......
Using y ......
I = 5
Wait ......
Using y ......
4. Discussions on wait (), notify (), policyall (), suspend (), resume (), and sleep ()
4.1 differences between the two groups of functions
1) When wait () causes the current thread to enter the stagnant state, it will also release the "Lock mark" occupied by the current thread, so that the synchronized Resources in the thread object can be used by other threads in the object; when the suspend () and sleep () enable the current thread to enter the stuck state, the "Lock mark" occupied by the current thread will not be released ".
2) the previous Group of functions must be called in the synchronized function or synchronized block; otherwise, an error occurs during running; the other group of functions can be called in the non-synchronized function and synchronized block.
4.2 trade-off between the two groups of functions
Java2 does not recommend using the last group of functions. Because the "Lock mark" obtained by the current thread is not released when wait () is called, it is easy to cause a "deadlock ".
Related Article

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.