2016-10-20 65 views
-2

有人可以幫我解決這個多線程問題嗎?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(); 
     } 
    } 
} 
+1

很酷!你試過什麼了? –

+0

@尼古拉斯這是我的代碼。它在執行主函數時拋出異常 – sarath

回答

0

創建一個同步的方法來遞增的值。當一個方法被識別爲同步時,一次只有一個線程可以訪問它,其他線程在它們可以訪問該方法之前等待初始線程完成方法執行。

請檢查How to synchronize a static variable among threads running different instances of a class in java?

+0

public class ThreadInitiator {public static ThreadInitiator { \t public static void main(String [] args){ \t \t RunnableSample runnableSample = new RunnableSample(); \t \t Thread thread1 = new Thread(runnableSample,「T1」); \t \t Thread thread2 = new Thread(runnableSample,「T2」); \t \t Thread thread3 = new Thread(runnableSample,「T3」); \t \t對(INT I = 0; I <9;我++){ \t \t \t thread1.start(); \t \t \t thread2.start(); \t \t \t thread3.start(); \t \t} \t} } – sarath

+0

在主要方法中做什麼這樣的事情。 – sarath