異なるクラスの 2 つの異なるインスタンスを実行する 2 つの別個のスレッドを用意し、同時に 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
私が欲しいもの
1
100
2
99
3
98
彼らはそのように交代する必要はありませんが、次々とではなく、同時に作業する必要があります。ヒント、アドバイス、またはコード スニペットをいただければ幸いです。