我无法理解控件是如何从" Expl Thread"输出语句到"主线程"输出声明。
package com.myjava.threads;
class MyRunnableThread implements Runnable {
public static int myCount = 0;
public MyRunnableThread() {
}
public void run() {
while (MyRunnableThread.myCount <= 10) {
try {
System.out.println("Expl Thread: " + (++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedException iex) {
System.out.println("Exception in thread: " + iex.getMessage());
}
}
}
}
public class RunMyThread {
public static void main(String a[]) {
System.out.println("Starting Main Thread...");
MyRunnableThread mrt = new MyRunnableThread();
Thread t = new Thread(mrt);
t.start();
while (MyRunnableThread.myCount <= 10) {
try {
System.out.println("Main Thread: " + (++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedException iex) {
System.out.println("Exception in main thread: " + iex.getMessage());
}
}
System.out.println("End of Main Thread...");
}
}
The output is:
启动主线程......
Main Thread: 1
Expl Thread: 2
Main Thread: 3
Expl Thread: 4
Main Thread: 5
Expl Thread: 6
Main Thread: 7
Expl Thread: 8
Main Thread: 9
Expl Thread: 10
Main Thread: 11
End of Main Thread...
答案 0 :(得分:2)
控件如何从“Expl Thread”输出语句转换为“Main Thread”输出语句。
未传递控制权。相反,每个线程都在调用
Thread.sleep(100);
由于这是相同的时间,他们轮流。将其中一个更改为sleep(50)
,您将看到一个打印消息的速度是原来的两倍。
答案 1 :(得分:1)
没有传输的控件......线程每100毫秒独立打印到控制台。由于时间是相同的,所以看起来他们轮流&#34;但是&#34;首先&#34;不确定。
更改其中一个Thread.sleep(100);
值,您会看到一个将比另一个更长/更短来打印。
答案 2 :(得分:0)
这是线程调度程序决定的内容。当您启动线程时,它将与已经存在的其他线程并行运行。它由线程调度程序决定分配给每个线程的顺序和时间。
无法保证执行顺序。