Home  >  Article  >  Java  >  Detailed explanation of thread yield() and thread sleep sleep() methods in Java

Detailed explanation of thread yield() and thread sleep sleep() methods in Java

高洛峰
高洛峰Original
2017-01-05 15:42:581984browse

Thread concession: yield()
The function of yield() is concession. It allows the current thread to enter the "ready state" from the "running state", thereby allowing other waiting threads with the same priority to obtain execution rights; however, there is no guarantee that after the current thread calls yield(), other waiting threads will have the same priority. The thread will definitely be able to obtain execution rights; it is also possible that the current thread has entered the "running state" and continues to run!
Example:

class ThreadA extends Thread{
  public ThreadA(String name){ 
    super(name); 
  } 
  public synchronized void run(){ 
    for(int i=0; i <10; i++){ 
      System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i); 
      // i整除4时,调用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();
  } 
}

(A certain time) running 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 [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
t2 [5]:8
t2 [5]:9

Result description:
"Thread t1" did not switch to "when it could be an integer of 4" Thread t2". This shows that although yield() can allow a thread to enter the "ready state" from the "running state"; however, it does not necessarily allow other threads to obtain CPU execution rights (that is, other threads enter the "running state"), even if this "Other threads" have the same priority as the thread currently calling yield().

Comparison of yield() and wait():
We know that the function of wait() is to make the current thread enter the "waiting (blocking) state" from the "running state" and also release it. Sync lock. The function of yield() is to give in, it will also make the current thread leave the "running state". The difference between them is:
(1) wait() allows the thread to enter the "waiting (blocking) state" from the "running state", while yield() allows the thread to enter the "ready state" from the "running state" ".
(2) wait() will cause the thread to release the synchronization lock of the object it holds, but the yield() method will not release the lock.
The following example demonstrates that yield() will not release the lock:

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(){ 
      // 获取obj对象的同步锁
      synchronized (obj) {
        for(int i=0; i <10; i++){ 
          System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i); 
          // i整除4时,调用yield
          if (i%4 == 0)
            Thread.yield();
        }
      }
    } 
  } 
}

(a certain time) running 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

Result description:
The main thread main is started Two threads t1 and t2. t1 and t2 will reference the synchronization lock of the same object in run(), that is, synchronized(obj). During the running of t1, although it will call Thread.yield(); however, t2 will not obtain the cpu execution right. Because, t1 did not release the "synchronization lock held by obj"!

Thread sleep: sleep()
sleep() is defined in Thread.java.
The function of sleep() is to make the current thread sleep, that is, the current thread will enter the "sleep (blocked) state" from the "running state". sleep() will specify the sleep time, and the thread sleep time will be greater than/equal to the sleep time; when the thread is awakened again, it will change from "blocked state" to "ready state", thus waiting for the CPU's scheduling execution.
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.getName(), i); 
        // i能被4整除时,休眠100毫秒
        if (i%4 == 0)
          Thread.sleep(100);
      } 
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  } 
} 
 
public class SleepTest{ 
  public static void main(String[] args){ 
    ThreadA t1 = new ThreadA("t1"); 
    t1.start(); 
  } 
}

Running result:

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

Result description:
The program is relatively simple, start thread t1 in the main thread main. After t1 is started, when the calculation i in t1 is divisible by 4, t1 will sleep for 100 milliseconds through Thread.sleep(100).

Comparison of sleep() and wait():
We know that the function of wait() is to make the current thread enter the "waiting (blocking) state" from the "running state" and also release it. Sync lock. The function of sleep() is to make the current thread enter the "sleep (blocked) state" from the "running state".
However, wait() will release the synchronization lock of the object, but sleep() will not release the lock.
The following example demonstrates that sleep() will 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(){ 
      // 获取obj对象的同步锁
      synchronized (obj) {
        try {
          for(int i=0; i <10; i++){ 
            System.out.printf("%s: %d\n", this.getName(), i); 
            // i能被4整除时,休眠100毫秒
            if (i%4 == 0)
              Thread.sleep(100);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    } 
  } 
}

Running results:

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 the main thread main. t1 and t2 will reference the synchronization lock of the same object in run(), that is, synchronized(obj). During the running of t1, although it will call Thread.sleep(100); however, t2 will not obtain the cpu execution right. Because, t1 did not release the "synchronization lock held by obj"!
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 commenting 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(){ 
      // 获取obj对象的同步锁
//      synchronized (obj) {
        try {
          for(int i=0; i <10; i++){ 
            System.out.printf("%s: %d\n", this.getName(), i); 
            // i能被4整除时,休眠100毫秒
            if (i%4 == 0)
              Thread.sleep(100);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
//      }
    } 
  } 
}


For more detailed explanations of thread yield() and thread sleep sleep() methods in Java, please pay attention to related articles. PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn