What is difference between sleep() method and yield() method of multi threading?

前端 未结 12 1774
野的像风
野的像风 2020-12-22 17:02

As currently executing thread while it encounters the call sleep() then thread moves immediately into sleeping stat. Whereas for yield() thread moves into runnable

12条回答
  •  借酒劲吻你
    2020-12-22 17:11

    One way to request the current thread to relinquish CPU so that other threads can get a chance to execute is to use yield in Java.

    yield is a static method. It doesn't say which other thread will get the CPU. It is possible for the same thread to get back the CPU and start its execution again.

    public class Solution9  {
    
    public static void main(String[] args) {
            yclass yy = new yclass ();
            Thread t1= new Thread(yy);
            t1.start();
            for (int i = 0; i <3; i++) {
                Thread.yield();
                System.out.println("during yield control => " + Thread.currentThread().getName());
            }
        }
    }
    
    class yclass implements Runnable{
    
        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                System.out.println("control => " + Thread.currentThread().getName());
            }
        }
    }
    

提交回复
热议问题