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

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

Jan 05, 2017 pm 03:42 PM

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();
  } 
}
Copy after login

(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
Copy after login

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();
        }
      }
    } 
  } 
}
Copy after login

(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
Copy after login

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(); 
  } 
}
Copy after login

Running result:

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

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();
        }
      }
    } 
  } 
}
Copy after login

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
Copy after login

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();
        }
//      }
    } 
  } 
}
Copy after login


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


Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles