2016-10-20 10 views
-2

このマルチスレッドの問題を解決するのに手伝ってくれる人はいますか?ループ内の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(); 
     } 
    } 
} 
+1

cool!これまでに何を試しましたか? –

+0

@ニコラスこれは私のコードです。メイン関数の実行中に例外をスローしています。 – sarath

答えて

0

を値をインクリメントする同期メソッドを作成します。メソッドが同期されていると識別されると、一度にアクセスできるのは1つのスレッドだけで、他のスレッドはメソッドにアクセスする前に最初のスレッドがメソッドの実行を完了するのを待ちます。

Pls check How to synchronize a static variable among threads running different instances of a class in java?

+0

パブリッククラスThreadInitiator { \t public static void main(String [] args){ \t \t RunnableSample runnableSample = new; \t \tスレッドスレッド1 =新規スレッド(runnableSample、 "T1"); \t \tスレッドthread2 =新しいスレッド(runnableSample、 "T2"); \t \tスレッドスレッド3 =新規スレッド(runnableSample、 "T3"); { \t \t \t thread1.start()(; iが9 sarath

+0

メインメソッドでこれをどうするか? – sarath

関連する問題