Explain the thread concessions in Java yield () and thread hibernation Sleep () method _java

Source: Internet
Author: User
Tags sleep static class

Thread Concession: Yield ()
the role of yield () is to give in. It allows the current thread to move from "Run state" to "ready state", this allows other waiting threads with the same priority to get execution rights, but there is no guarantee that after the current thread calls yield (), other threads with the same priority will be able to execute; it may also be that the current thread has entered the Run status "continue running!"
Example:

Class Threada extends thread{public
  Threada (String name) { 
    super (name); 
  } 
  Public synchronized void Run () {to 
    (int i=0 i <10; i++) { 
      System.out.printf ("%s [%d]:%d\n", This.getname (), This.getpriority (), i); 
      I divide 4 o'clock, call yield
      if (i%4 = 0)
        Thread.yield (); 

}}} public class yieldtest{public 
  static void Main (string[] args) { 
    Threada t1 = new Threada ("T1"); 
    Threada t2 = new Threada ("T2"); 
    T1.start (); 
    T2.start ();
  } 
 

(of one) run result:

T1 [5]:0
T2 [5]:0
T1 [5]:1
t1 [5]:2 t1
[5]:3 T1]
[5]:4
t1
[5]:5 t1] [5]:6 T1] [a] [5]:7 t1 [5]:8
T1 [5]:9
T2 [5]:1
T2 [5]:2 T2]
[5]:3
T2 [5]:4 T2
[5]:5
T2 [5]:6 T2] [5]:7< c18/>t2 [5]:8
T2 [5]:9

Results show:
Thread T1 does not switch to thread T2 when it can be 4 integers. This indicates that yield () may allow the thread to enter the "Ready state" by "run State"; However, it does not necessarily give the other threads access to CPU execution (that is, other threads enter the "Run State"), even if this "other thread" has the same priority as the thread that is currently calling yield ().

Comparison of yield () with wait ():
as we know, the effect of Wait () is to allow the current thread to enter the standby (blocking) state while it is running, releasing the sync lock. The role of yield () is to give in, and it will leave the current thread out of the "running state." The difference between them is:
(1) Wait () is to let the thread from "Run state" to "waiting (blocking) state", and not yield () is to let the thread from "Run state" into the ready state.
(2) A wait () is a thread that releases the synchronized lock of the object it holds, while the yield () method does not release the lock.
The following example shows that yield () does not release locks:

public class yieldlocktest{ 

  private static Object obj = new Object ();

  public static void Main (string[] args) { 
    Threada t1 = new Threada ("T1"); 
    Threada t2 = new Threada ("T2"); 
    T1.start (); 
    T2.start ();
  } 

  Static class Threada extends thread{public
    Threada (String name) { 
      super (name); 
    } 
    public void Run () { 
      //Get the synchronization lock
      synchronized (obj) for obj object (
        int i=0 i <10; i++) { 
          System.out.printf ("%s [%d]:%d\n", This.getname (), this.getpriority (), i); 
          I divide 4 o'clock, call yield
          if (i%4 = 0)
            Thread.yield ();
        } 
  } 
}} 

(one time) run result:

T1 [5]:0
T1 [5]:1
T1 [5]:2
T1 [5]:3
T1 [5]:4 T1]
[5]:5 t1
[5]:6 t1] [5]:7 T1 [5] : 8
T1 [5]:9
T2 [5]:0
T2 [5]:1
T2 [5]:2
T2
[5]:3 T2] [5]:4 T2 [5]:5 T2] [5]:6
T2 [5]:7
T2 [5]:8
T2 [5]:9

Results show:
Two threads T1 and T2 are started in main thread main. T1 and T2 in run () refer to the synchronization lock for the same object, that is, synchronized (obj). While the T1 is running, it will call Thread.yield (), but T2 will not get CPU execution power. Because, T1 does not release "the synchronization lock which obj holds"!

Thread Hibernate: Sleep ()
sleep () is defined in Thread.java.
The function of sleep () is to let the current thread hibernate, that is, the current thread will go from "Run state" to "hibernate (blocked) state". Sleep () Specifies the time of hibernation, when the thread sleeps longer than/equal to the sleep time; When the thread is awakened, it becomes "ready" by the blocking state, which waits for the CPU's dispatch to execute.
Example:

Class Threada extends thread{public
  Threada (String name) { 
    super (name); 
  } 
  Public synchronized void Run () { 
    try {
      for (int i=0 i <10; i++) { 
        System.out.printf ("%s:%d\n", This.getnam E (), i); 
        I can be divisible by 4, hibernate 100 ms
        if (i%4 = = 0)
          thread.sleep;
      } 
    catch (Interruptedexception e) {
      E.printstacktrace (); 

}} public class sleeptest{public 
  static void Main (string[] args) { 
    Threada t1 = new Threada ("T1"); 
    T1.start (); 
  } 
 

Run Result:

t1:0
t1:1
t1:2
t1:3
t1:4
t1:5
t1:6 t1:7 t1:8 t1:9

Results show:
The program is relatively simple, starting thread T1 in main thread main. After the T1 is started, when the calculation I in T1 is divisible by 4, T1 sleeps 100 milliseconds through Thread.Sleep (100).

Comparison of sleep () with Wait ():
as we know, the effect of Wait () is to allow the current thread to enter the standby (blocking) state while it is running, releasing the sync lock. The function of sleep () is to allow the current thread to enter the hibernation (blocking) state by running state.
However, wait () releases the synchronization lock of the object, while sleep () does not release the lock.
The following example shows that sleep () does not release the lock.

public class sleeplocktest{ 

  private static Object obj = new Object ();

  public static void Main (string[] args) { 
    Threada t1 = new Threada ("T1"); 
    Threada t2 = new Threada ("T2"); 
    T1.start (); 
    T2.start ();
  } 

  Static class Threada extends thread{public
    Threada (String name) { 
      super (name); 
    } 
    public void Run () { 
      //Get the synchronous lock
      synchronized (obj) {
        try {for
          int i=0 i <10; i++) { 
            of the Obj object System.out.printf ("%s:%d\n", This.getname (), i); 
            I can be divisible by 4, hibernate 100 ms
            if (i%4 = = 0)
              thread.sleep;
          }
        catch (Interruptedexception e) {
          E.printstacktrace ();}}}} 
 

Run Result:

t1:0
t1:1
t1:2
t1:3
t1:4
t1:5
t1:6 t1:7 t1:8 t1:9 t2:0 T2:1
t2:2
t2:3
t2:4
t2:5
t2:6 t2:7 t2:8 t2:9

Result Description:
Two threads T1 and T2 are started in main thread main. T1 and T2 in run () refer to the synchronization lock for the same object, that is, synchronized (obj). While the T1 is running, it will call Thread.Sleep (100), but T2 will not get CPU execution power. Because, T1 does not release "the synchronization lock which obj holds"!
Note that if we comment out synchronized (obj) and execute the program again, T1 and T2 can switch to each other. The following is the source code after the annotation synchronized (obj):

public class sleeplocktest{ 

  private static Object obj = new Object ();

  public static void Main (string[] args) { 
    Threada t1 = new Threada ("T1"); 
    Threada t2 = new Threada ("T2"); 
    T1.start (); 
    T2.start ();
  } 

  Static class Threada extends thread{public
    Threada (String name) { 
      super (name); 
    } 
    public void Run () { 
      //Get the Synchronization lock
//      synchronized (obj) {
        try {for
          (int i=0 i <10; i++) of the Obj object { C18/>system.out.printf ("%s:%d\n", This.getname (), i); 
            I can be divisible by 4, hibernate 100 ms
            if (i%4 = = 0)
              thread.sleep;
          }
        catch (Interruptedexception e) {
          E.printstacktrace ();
        }
//      }
    } 
  } 
} 

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.