How does Thread.sleep() work when called from multiple threads

后端 未结 5 1953
暖寄归人
暖寄归人 2021-01-18 05:31

sleep() is a static method of class Thread. How does it work when called from multiple threads. and how does it figure out the current thread of execution. ?

or may

5条回答
  •  别那么骄傲
    2021-01-18 05:45

    When the virtual machine encounters a sleep(long)-statement, it will interrupt the Thread currently running. "The current Thread" on that moment is always the thread that called Thread.sleep(). Then it says:

    Hey! Nothing to do in this thread (Because I have to wait). I'm going to continue an other Thread.

    Changing thread is called "to yield". (Note: you can yield by yourself by calling Thread.yield();)

    So, it doesn't have to figure out what the current Thread is. It is always the Thread that called sleep(). Note: You can get the current thread by calling Thread.currentThread();

    A short example:

    // here it is 0 millis
    blahblah(); // do some stuff
    // here it is 2 millis
    new Thread(new MyRunnable()).start(); // We start an other thread
    // here it is 2 millis
    Thread.sleep(1000);
    // here it is 1002 millis
    

    MyRunnable its run() method:

    // here it is 2 millis; because we got started at 2 millis
    blahblah2(); // Do some other stuff
    // here it is 25 millis;
    Thread.sleep(300); // after calling this line the two threads are sleeping...
    // here it is 325 millis;
    ... // some stuff
    // here it is 328 millis;
    return; // we are done;
    

提交回复
热议问题