当前位置:网站首页>Yield method of tread

Yield method of tread

2022-07-06 07:06:00 chengqiuming

One   The finishing touch

yiled  Method is a heuristic method , It will remind the scheduler that I am willing to give up the current  CPU  free , If  CPU  Our resources are not tight , Will ignore this reminder .

call  yield  Method causes the current thread to change from  RUNNING The state switches to  RUNNABLE  state , Generally, this method is not commonly used .

Two   actual combat

1  Code  

package concurrent;

import java.util.stream.IntStream;

public class ThreadYield {
    public static void main(String[] args) {
        IntStream.range(0, 2).mapToObj(ThreadYield::create).forEach(Thread::start);
    }


    private static Thread create(int index) {
        return new Thread(() -> {
//            if (index == 0) {
//                Thread.yield();
//            }
            System.out.println(index);
        });
    }
}

2  test

The above program runs many times , You will find that the output results are inconsistent , Sometimes it's printing 0, Sometimes it's printing 1.

Open the comment and then run , You will find that the output results are still inconsistent , Sometimes it's printing 0, Sometimes it's printing 1.

3  explain  

In general , Because if the first thread obtains  CPU  resources , It will be modest , Initiative to tell  CPU  The scheduler releases its own resources , however  yield  Just a hint ( hint ),CPU  The scheduler does not guarantee that it will meet every time  yield  Tips .

yield  The procedure is not controllable , So this method is not commonly used .

3、 ... and  yield  and  sleep  Comparison of

  • sleep  Causes the current thread to pause for a specified time , No,  CPU  Time slice consumption .
  • yield  Just for  CPU  A hint from the scheduler , If  CPU  The scheduler did not ignore this prompt , It will lead to the switching of thread context .
  • sleep  Makes the thread short  block, Will be released within the specified time  CPU  resources .
  • yield  Can make  RUNNING  State of  Thread  Get into  RUNNABLE  state ( If  CPU  If the scheduler does not ignore this prompt )
  • sleep  Almost 100% complete the sleep for a given time , and  yield  Your prompt does not necessarily guarantee .
  • One thread  sleep Another thread called  interrupt  An interrupt signal will be captured , and  yield  Will not be .

原网站

版权声明
本文为[chengqiuming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131946558278.html