我有这个程序有 3 个线程来显示数字 1-10。我希望它们按顺序输出,但目前它在跳来跳去。示例 0 1 2 3 4 5 6 7 8 9
我在论坛中环顾四周,它显示 Thread.yield(); 将解决这个问题,但在我输入 Thread.yield(); 它仍然一样
public class ThreadTest
{
public static void main(String [] args)
{
MyThread t1 = new MyThread(0, 3, 10);
MyThread t2 = new MyThread(1, 3, 10);
MyThread t3 = new MyThread(2, 3, 10);
t1.start();
t2.start();
t3.start();
}
}
public class MyThread extends Thread {
private int startIdx, nThreads, maxIdx;
public MyThread(int s, int n, int m) {
this.startIdx = s;
this.nThreads = n;
this.maxIdx = m;
}
@Override
public void run() {
for (int i = this.startIdx; i < this.maxIdx; i += this.nThreads) {
System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();
}
}
}
output:
[ID 8] 0
[ID 8] 3
[ID 8] 6
[ID 10] 2
[ID 10] 5
[ID 10] 8
[ID 9] 1
[ID 8] 9
[ID 9] 4
[ID 9] 7