-2

Can someone help me to solve this multi-threading problem ?

The program should initiate three threads with a common resource. Each thread should print a incremented count value. Sample output is mentioned below. where T1,T2 and T3 are threads.

T1  T2  T3

1   2   3    

4   5   6

7   8   9

My current code:

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();
        }
    }
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
sarath
  • 1
  • 1

1 Answers1

0

Create a synchronized method to increment the value. When a method is identified as synchronized, only one thread can access it at a time and the other threads wait for the initial thread to complete method execution before they can access the method.

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

Community
  • 1
  • 1
HARDI
  • 394
  • 5
  • 12
  • 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 Oct 20 '16 at 18:04
  • what to do something like this in the main method. – sarath Oct 20 '16 at 18:04