考慮具有下面的類:爲什麼最低優先級和最高優先級的線程仍然交錯?
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo(String name) {
threadName = name;
System.out.println("Creating thread " + threadName);
}
@Override
public void run() {
System.out.println("Running thread" + threadName);
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread " + threadName + ", iteration: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println(threadName + " exiting.");
}
public void Fire (int priority) {
System.out.println("Starting thread " + threadName);
if (t == null) {
t = new Thread (this, threadName);
t.setPriority(priority);
t.start();
}
}
}
而另一個類來測試它:
public class TestThread {
public TestThread() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
RunnableDemo R1 = new RunnableDemo("RunnableDemo-One");
RunnableDemo R2 = new RunnableDemo("RunnableDemo-Two");
R1.Fire(Thread.MAX_PRIORITY);
R2.Fire(Thread.MIN_PRIORITY);
}
}
此代碼段的輸出時運行爲:
Creating thread RunnableDemo-One
Creating thread RunnableDemo-Two
Starting thread RunnableDemo-One
Starting thread RunnableDemo-Two
Running threadRunnableDemo-One
Thread RunnableDemo-One, iteration: 4
Running threadRunnableDemo-Two
Thread RunnableDemo-Two, iteration: 4
Thread RunnableDemo-Two, iteration: 3
Thread RunnableDemo-One, iteration: 3
Thread RunnableDemo-Two, iteration: 2
Thread RunnableDemo-One, iteration: 2
Thread RunnableDemo-Two, iteration: 1
Thread RunnableDemo-One, iteration: 1
RunnableDemo-Two exiting.
RunnableDemo-One exiting.
換句話說,儘管一個線程具有MAX_PRIORITY,另一個線程具有MIN_PRIORITY,但系統仍然在它們之間交錯,就好像它們具有相同的優先級。 這是爲什麼?
措辭相同的問題不同的:有一個場景或代碼修改了該程序的輸出將是:
Thread RunnableDemo-One, iteration: 4
Thread RunnableDemo-One, iteration: 3
Thread RunnableDemo-One, iteration: 2
Thread RunnableDemo-One, iteration: 1
Thread RunnableDemo-Two, iteration: 4
Thread RunnableDemo-Two, iteration: 3
Thread RunnableDemo-Two, iteration: 2
Thread RunnableDemo-Two, iteration: 1
也就是說,同時仍保持它們作爲單獨的和獨立的線程?
爲什麼線程2會在沒有做任何工作的情況下四處閒逛,而線程一是*睡眠*?如果高優先級的線程決定休眠多天,你會期望它不會完成任何工作嗎?優先級是分配CPU時間......當一個線程正在休眠時,它不使用CPU時間。 –
你的CPU可以並行運行兩個線程嗎? – John
在問這樣一個問題之前,你需要刷新你的多重編程基礎知識。 –