このマルチスレッドの問題を解決するのに手伝ってくれる人はいますか?ループ内のJavaマルチスレッド/スレッドの開始
プログラムは、共通のリソースを持つ3つのスレッドを開始する必要があります。各スレッドはインクリメントされたカウント値を出力する必要があります。サンプル出力は以下のとおりです。 T1、T2、T3はスレッドです。
T1 T2 T3
1 2 3
4 5 6
7 8 9
私の現在のコード:
public class RunnableSample implements Runnable {
static int count = 0;
public void run() {
synchronized (this) {
count++;
System.out.println(
"Current thread : Thread name :" + Thread.currentThread().getName()
+ " Counter value :" + count
);
}
}
}
//main method with for loop for switching between the threads
public class ThreadInitiator {
public static void main(String[] args) {
RunnableSample runnableSample = new RunnableSample();
Thread thread1 = new Thread(runnableSample, "T1");
Thread thread2 = new Thread(runnableSample, "T2");
Thread thread3 = new Thread(runnableSample, "T3");
for (int i = 0; i < 9; i++) {
thread1.start();
thread2.start();
thread3.start();
}
}
}
cool!これまでに何を試しましたか? –
@ニコラスこれは私のコードです。メイン関数の実行中に例外をスローしています。 – sarath