我希望有两个独立的线程分别运行不同类的实例,并且希望它们同时执行run命令。
我创建了一个示例类来演示我遇到的问题。一个选手向前数数,另一个向后数数。
public class testCount {
public static void main(String args[]) {
testCount countCompetition = new testCount();
countCompetition.run();
}
public void run() {
(new Thread(new racer1())).start();
(new Thread(new racer2())).start();
}
public class racer1 implements Runnable {
public void run() {
for(int x = 0; x < 100; x++) {
System.out.println(x);
}
}
}
public class racer2 implements Runnable {
public void run() {
for(int y = 100; y > 0; y--) {
System.out.println(y);
}
}
}
}
我的结果
1
2
... All the way to 100
100
100
99
... All the way back down
1
What I want
1
100
2
99
3
98
他们不需要那样轮流工作,但是他们需要同时工作,而不是一个接一个地工作。 如有提示、建议或代码片段,将不胜感激。