Differences between yield (), sleep (), and wait () (revised version)

Source: Internet
Author: User

Differences between yield (), sleep (), and wait () in Java (revised version)
Http://qdisb.blogbus.com/logs/223774.html
There are multiple code errors in the original article, which are corrected here.
--------------------------------------------------------------

These three functions are often obfuscated.

From the operating system perspective, the OS maintains a ready queue (ready thread Queue ). In addition, at a certain time, the CPU only serves the thread in the queue header of the ready queue.
However, the thread being served may feel that the CPU service quality is not good enough, so it exits early, which is yield.
Or the thread that is currently being served needs to sleep for a while, and will continue to be served after waking up. This is sleep.

The sleep method is not recommended and can be used with wait.
It is best to implement this by yourself when the thread exits. It always checks a state in the running state. If this state is true, it will continue to run. If the outside world changes this state variable, the thread will stop running.

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 () 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.
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.

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.

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.

Thoroughly understand the multi-thread communication mechanism:

Inter-thread Communication
1. Several States of the thread
A thread has four States. Any thread must be in one of these four states:

1) generate (new): The thread object has been generated but has not been started, so it cannot be executed. For example, if a new thread object is generated without calling the START () function on it.

2) runnable: each system that supports multiple threads has a scheduler, which selects a thread from the thread pool and starts it. When a thread is in the executable state, it may be in the thread pool waiting for the scheduler to start it; or it may be being executed. For example, after the start () method of a thread object is executed, the thread is in the executable state, but it is obvious that the thread is not necessarily being executed at this time.

3) Dead: When a thread ends normally, it is in the dead state. For example, after a thread's run () function is executed, the thread enters the dead state.
4) blocked: When a thread is stuck, the system scheduler ignores it and does not schedule it. When a thread in the stuck state returns to the executable state, it may be re-executed. For example, after a thread calls the wait () function, the thread becomes stuck. It can return to the executable State only after the thread calls y or yyall again.

2. Common Function functions under Class thread
2.1 suspend (), resume ()

1) The suspend () function can cause the thread to enter the stuck state. After the thread enters the stuck State through suspend (), the thread will not change back to the executable State unless the resume () message is received.
2) When the suspend () function is called, the thread will not release its "lock flag ".
Example 11:

 public class MyTest {  public static void main(String[] args) {    TestThreadMethod t1 = new TestThreadMethod("t1");    TestThreadMethod t2 = new TestThreadMethod("t2");    t1.start();// (5)    // t1.start(); //(3)    t2.start();// (4)  }}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 < 5; i++) {        shareVar++;        if (shareVar == 5) {          this.suspend();// (1)        }      }    } else {      System.out.print(Thread.currentThread().getName());      System.out.println(" shareVar = " + shareVar);      this.resume();// (2)    }  }}

The running result is:

T2 sharevar = 5

I. When the thread generated by code T1 (5) runs at code (1), the thread enters the stuck state. Then the scheduler calls the thread produced by T2 of code (4) from the thread pool. At this time, the sharevar value is not 0, so the statement in else is executed.
Ii. Maybe you will ask, why does T1 not enter the executable status after Code Execution (2? As mentioned above, t1 and t2 are two threads of different objects, while code (1) and (2) only operate on the current object, so the result of thread Execution Code (1) produced by T1 is that the current thread of the object T1 enters the stuck state, and the thread Execution Code generated by T2 (2) the result is to call all the threads in the stopped state of the object T2 back to the executable state.
Iii. Now I have commented out code (4) and removed the comments of code (3). Can T1 be re-executed? The running result is nothing. Why? You may think that when the thread produced by code (5) is executed to code (1), it enters the stuck state; while code (3) the generated thread and the thread produced by code (5) belong to the same object, so when the thread produced by code (3) is executed to code (2, the execution of the thread generated by code (5) can be returned to the executable state. Note that the suspend () function only stops the current thread, but does not release the lock mark obtained by the current thread ". Therefore, when the threads produced by code (5) enter the stuck state, the threads produced by code (3) still cannot be started, because the lock mark of the current object is still occupied by the thread generated by code (5.

2.2 sleep ()
1) The sleep () function has a parameter that enables the thread to enter the stuck state within the specified time. After the specified time, the thread automatically enters the executable state.
2) When the sleep () function is called, the thread will not release its "lock mark ".
Example 12:

 class TestThreadMethod extends Thread {  public static int shareVar = 0;  public TestThreadMethod(String name) {    super(name);  }  public synchronized void run() {    for (int i = 0; i < 3; i++) {      System.out.print(Thread.currentThread().getName());      System.out.println(" : " + i);      try {        Thread.sleep(100);// (4)      } catch (InterruptedException e) {        System.out.println("Interrupted");      }    }  }}public class MyTest {  public static void main(String[] args) {    TestThreadMethod t1 = new TestThreadMethod("t1");    TestThreadMethod t2 = new TestThreadMethod("t2");    t1.start(); // (1)    t1.start(); // (2)    // new Thread(t1).start();// (4)    // new Thread(t1).start();// (5)    // new Thread(t2).start(); (3)t2.start();  }}

The running result is:

Reference:
Exception in thread "Main" Java. Lang. illegalthreadstateexception
T1: 0
At java. Lang. thread. Start (unknown source)
At mytest. Main (mytest. Java: 26)
T1: 1
T1: 2

It can be seen that an exception occurs when the same object is directly started twice.
If we comment out (1) and (2) and change it to the Code (4) and (5), the running result is:

Reference:
Thread-0: 0
Thread-0: 1
Thread-0: 2
Thread-1: 0
Thread-1: 1
Thread-1: 2

The results show that although sleep () is executed in run (), it does not release the object's "lock flag", unless the code (1) the thread executes the run () function and releases the "Lock mark" of the object. Otherwise, the thread of code (2) will never be executed.

If you comment out code (2) and remove the code (3), the result will be changed:

Reference:
Thread-0: 0
Thread-1: 0
Thread-0: 1
Thread-1: 1
Thread-1: 2
Thread-0: 2

Because t1 and t2 are the threads of two objects, when thread T1 is stuck through sleep (), the scheduler will call other executable threads from the thread pool, thus thread T2 is started.

Example 13:

 class TestThreadMethod extends Thread {  public static int shareVar = 0;  public TestThreadMethod(String name) {    super(name);  }  public synchronized void run() {    for (int i = 0; i < 5; i++) {      System.out.print(Thread.currentThread().getName());      System.out.println(" : " + i);      try {        if (Thread.currentThread().getName().equals("t1"))          Thread.sleep(200);        else          Thread.sleep(100);      } catch (InterruptedException e) {        System.out.println("Interrupted");      }    }  }}public class MyTest {  public static void main(String[] args) {    TestThreadMethod t1 = new TestThreadMethod("t1");    TestThreadMethod t2 = new TestThreadMethod("t2");    t1.start();    // t1.start();    t2.start();  }}

The running result is:

Reference:
T1: 0
T2: 0
T2: 1
T1: 1
T2: 2
T2: 3
T1: 2
T2: 4
T1: 3
T1: 4

Thread T1 calls sleep (200) and thread T2 calls sleep (100), so the time when thread T2 is in the stuck state is half of thread T1, from the result, the thread T2. T2.

2.3 yield ()
1) The yield () function enables the thread to enter the executable state, and the scheduler re-runs the scheduler from the thread in the executable state. Therefore, the function that calls yield () may be executed immediately.
2) When the yield () function is called, the thread will not release its "lock mark ".
Example 14:

 class TestThreadMethod extends Thread {  public static int shareVar = 0;  public TestThreadMethod(String name) {    super(name);  }  public synchronized void run() {    for (int i = 0; i < 4; i++) {      System.out.println(Thread.currentThread().getName() + " : " + i);      Thread.yield();    }  }}public class MyTest {  public static void main(String[] args) {    TestThreadMethod t1 = new TestThreadMethod("t1");    TestThreadMethod t2 = new TestThreadMethod("t2");    new Thread(t1).start();    new Thread(t1).start();// (1)    // new Thread(t2).start(); //(2)  }}

The running result is:

Reference:
Thread-0: 0
Thread-0: 1
Thread-0: 2
Thread-0: 3
Thread-1: 0
Thread-1: 1
Thread-1: 2
Thread-1: 3

The results show that the "Lock flag" of the object is not released when yield () is called ".
If you comment out code (1) and remove the comments of code (2), the result is:

Reference:
Thread-0: 0
Thread-1: 0
Thread-0: 1
Thread-1: 1
Thread-0: 2
Thread-1: 2
Thread-0: 3
Thread-1: 3

According to the results, although the T1 thread calls yield (), it is immediately executed again.
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.println(Thread.currentThread().getName() + " : " + i);      // Thread.yield(); (1)      /* (2) */      try {        Thread.sleep(300);      } catch (InterruptedException e) {        System.out.println("Interrupted");      }    }  }}public class MyTest {  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:

Reference:
T1: 0
T2: 0
T1: 1
T2: 1
T1: 2
T2: 2
T1: 3
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:

Reference:
T1: 0
T1: 1
T2: 0
T1: 2
T1: 3
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(300);      } catch (InterruptedException e) {        System.out.println("Interrupted");      }    }  }}public class MyTest {  public static void main(String[] args) {    TestThreadMethod t1 = new TestThreadMethod("t1");    TestThreadMethod t2 = new TestThreadMethod("t2");    t1.start();    try {      t1.join();    } catch (InterruptedException e) {}    t2.start();  }}

The running result is:

Reference:
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.notify();// (5)    }  }}public class MyTest {  public static void main(String[] args) {    TestThreadMethod t1 = new TestThreadMethod("t1");    TestThreadMethod t2 = new TestThreadMethod("t2");    new Thread(t1).start();// (1)    // new Thread(t1).start(); // (2)    new Thread(t2).start();// (3)  }}

The running result is:

Reference:
Thread-1 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:

Reference:
Thread-1 sharevar = 5
Thread-0 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 be synchronized is not the current object */synchronized (TTM) {system. out. println ("policy ...... "); TTM. notify () ;}}} public class mytest {public static void main (string [] ARGs) {testthreadmethod T1 = new testthreadmethod ("T1"); t1.start ();}}

The running result is:

Reference:
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 ......
Using y ......
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 ".

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.