Java multithreading yield comment sharing

  • 2020-04-01 02:39:09
  • OfStack

Thread.yield() method:

Changes the current thread from execution state (run state) to executable state (ready state). The CPU selects from a number of executable states, which means that the current thread may be reexecuted, not that another thread is bound to be executed and will not be executed the next time.

There is a thread.yield () method in Java threads, which many people translate as Thread yield. As the name implies, when a thread USES this method, it will allow its own CPU to execute the time, let itself or other threads run.

For example: there are so many people waiting in line to go to the bathroom that when it's their turn to go to the bathroom, all of a sudden this person says, "I'm going to have a race to see who can get to the bathroom first!" ", and then all the people at the same starting line rushed to the toilet, it may be someone else grabbed, he may have grabbed. We also know that threads have a priority problem, so do these people who have priority have to be able to grab the toilet? Not necessarily, they are just the probability of some larger, may not have the privilege of the snatch.

Example:


package com.yield;
public class YieldTest extends Thread {
 public YieldTest(String name) {
  super(name);
 }
 @Override
 public void run() {
  for (int i = 1; i <= 50; i++) {
   System.out.println("" + this.getName() + "-----" + i);
   //When I is 30, the thread loses CPU time and allows another or its own thread to execute (i.e., whoever gets the first one to execute)
   if (i == 30) {
    this.yield();
   }
  }
 }
 public static void main(String[] args) {
  YieldTest yt1 = new YieldTest(" Zhang SAN ");
  YieldTest yt2 = new YieldTest(" Li si ");
  yt1.start();
  yt2.start();
 }
}

Operation results:

In the first case, when the thread reaches 30, the CPU time is lost, and the thread grabs the CPU time and executes.

< img border = 0 SRC = "/ / img.jbzj.com/file_images/article/201312/20131221152200176.jpg" >

The second case: lee si (thread) loses CPU time when the execution reaches 30, at which point lee si (thread) grabs the CPU time and executes.

< img border = 0 SRC = "/ / img.jbzj.com/file_images/article/201312/20131221152251871.jpg" >


Related articles: