有人可以幫我解決這個多線程問題嗎?Java多線程/啓動循環中的線程
程序應該用一個公共資源啓動三個線程。每個線程應打印一個增加的計數值。示例輸出如下所述。 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();
}
}
}
很酷!你試過什麼了? –
@尼古拉斯這是我的代碼。它在執行主函數時拋出異常 – sarath