簡體   English   中英

從多個線程調用時Thread.sleep()如何工作

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

sleep()是Thread類的靜態方法。 從多個線程調用時,它是如何工作的。 以及如何找出當前的執行線程。

或者可能是更通用的問題,將是如何從不同的線程調用靜態方法? 不會有並發問題嗎?

如何找出當前的執行線程?

不必。 它僅調用操作系統,該操作系統始終使調用它的線程休眠。

sleep方法會休眠當前線程,因此,如果您從多個線程中調用它,則會休眠每個線程。 另外還有currentThread靜態方法,該方法使您可以獲取當前正在執行的線程。

一個更通用的問題是如何從不同線程調用靜態方法? 不會有並發問題嗎?

如果一個或多個線程修改共享狀態而另一個線程使用相同狀態,則僅存在潛在的並發問題。 sleep()方法沒有共享狀態。

Thread.sleep(long)java.lang.Thread類中本地實現。 這是其API文檔的一部分:

 Causes the currently executing thread to sleep (temporarily cease 
 execution) for the specified number of milliseconds, subject to 
 the precision and accuracy of system timers and schedulers. The thread 
 does not lose ownership of any monitors.

sleep方法使調用它的線程進入睡眠狀態(基於EJP的注釋) 確定當前正在執行的線程(調用它並使它進入睡眠狀態)。 Java方法可以通過調用Thread.currentThread()確定哪個線程正在執行它。

可以同時從任意數量的線程中調用方法(靜態或非靜態)。 只要您的方法是線程安全的,那么Threre就不會有任何並發​​問題。 僅當多個線程在沒有適當同步的情況下修改類或實例的內部狀態時,您才會遇到問題。

當虛擬機遇到sleep(long)語句時,它將中斷當前正在運行的線程。 那一刻的“當前線程”始終是稱為Thread.sleep()的線程。 然后它說:

嘿! 該線程中無事可做(因為我必須等待)。 我將繼續另一個線程。

更改線程稱為“屈服”。 (注意:您可以通過調用Thread.yield();來自己屈服)

因此,不必弄清楚當前的線程是什么。 總是線程調用sleep()。 注意:您可以通過調用Thread.currentThread();獲得當前線程Thread.currentThread();

一個簡短的例子:

// 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

MyRunnablerun()方法:

// 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM