Thread Scheduling
In Java technology,threads are usually preemptive,but not necessarily Time-sliced(the process of giving each thread an equal amount of CPU time).It is common mistake to believe that "preemptive" is a fancy word for "does time-slicing".
For the runtime on a Solaris Operating Environment platform,Java technology does not preempt threads of the same priority.However,the runtime on Microsoft Windows platforms uses time-slicing,so it preempts threads of the same priority and even threads of higher priority.Preemption is not guaranteed;however,most JVM implementations result in behavior that appears to be strictly preemptive.Across JVM implementations,there is no absolute guarantee of preemption or time-slicing.The only guarantees lie in the coder’s use of wait and sleep.
The model of a preemptive scheduler is that many threads might be runnable,but only one thread is actually running.This thread continues to run until it ceases to be runnable or another thread of higher priority becomes runnable.In the latter case,the lower priority thread is preempted by the thread of higher priority,which gets a chance to run instead.
A thread might cease to runnable (that is,because blocked) for a variety of reasons.The thread’s code can execute a Thread.sleep() call,deliberately asking the thread to pause for a fixed period of time.The thread might have to wait to access a resource and cannot continue until that resource become available.
All thread that are runnable are kept in pools according to priority.When a blocked thread becomes runnable,it is placed back into the appropriate runnable pool.Threads from the highest priority nonempty pool are given CPU time.
The last sentence is worded loosed because:
(1) In most JVM implementations,priorities seem to work in a preemptive manner,although there is no guarantee that priorities have any meaning at all;
(2) Microsoft Window’s values affect thread behavior so that it is possible that a Java Priority 4 thread might be running,in spite of the fact that a runnable Java Priority 5 thread is waiting for the CPU.
In reality,many JVMs implement pool as queues,but this is not guaranteed hehavior.
線程調度(試翻譯,歡迎指正)
在java技術中,線程通常是搶占式的而不需要時間片分配進程(分配給每個線程相等的cpu時間的進程)。一個經常犯的錯誤是認為“搶占”就是“分配時間片”。
在Solaris平台上的運行環境中,相同優先級的線程不能相互搶占對方的cpu時間。但是,在使用時間片的windows平台運行環境中,可以搶占相同甚至更高優先級的線程的cpu時間。搶占並不是絕對的,可是大多數的JVM的實現結果在行為上表現出了嚴格的搶占。縱觀JVM的實現,並沒有絕對的搶占或是時間片,而是依賴於編碼者對wait和sleep這兩個方法的使用。
搶占式調度模型就是許多線程屬於可以運行狀態(等待狀態),但實際上只有一個線程在運行。該線程一直運行到它終止進入可運行狀態(等待狀態)或是另一個具有更高優先級的線程變成可運行狀態。在後一種情況下,底優先級的線程被高優先級的線程搶占,高優先級的線程獲得運行的機會。
線程可以因為各種各樣的原因終止並進入可運行狀態(因為堵塞)。例如,線程的代碼可以在適當時候執行Thread.sleep()方法,故意讓線程中止;線程可能為了訪問資源而不得不等待直到該資源可用為止。
所有可運行的線程根據優先級保持在不同的池中。一旦被堵塞的線程進入可運行狀態,它將會被放回適當的可運行池中。非空最高優先級的池中的線程將獲得cpu時間。
最後一個句子是不精確的,因為:
(1)在大多數的JVM實現中,雖然不能保證說優先級有任何意義,但優先級看起來象是用搶占方式工作。
(2)微軟windows的評價影響線程的行為,以至盡管一個處於可運行狀態的優先級為5的java線程正在等待cpu時間,但是一個優先級為4的java線程卻可能正在運行。
實際上,許多JVM用隊列來實現池,但沒有保證行為。