user3448119
user3448119

Reputation: 107

value is not incremented, thread

I am expecting below to increment c value to be 2. But I am always getting 1 output even after the 2nd thread started.

package test.main;

public class TestThread implements Runnable {
    private int c=0;

    @Override
    public void run() {
        synchronized(this){
        c=c+1;
        //wait(1000);
        go();
        }

    }

    private void go() {
        System.out.println("Thread name :"+Thread.currentThread()+" in go() : "+c);
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("main()");
        Thread t1 =  new Thread(new TestThread(),"thread1");
        Thread t2 =  new Thread(new TestThread(),"thread2");
        t1.start();
        t2.start(); 

    }
}

Upvotes: 0

Views: 43

Answers (4)

user3294068
user3294068

Reputation: 350

Each TestThread object has its own copy of c, so each will be incremented only once.

Upvotes: 1

stinepike
stinepike

Reputation: 54682

In thread t1 and t2 you are passing two completely different objects. So in both cases it is incrementing their own c which are not related to each other.

Use a single object

    TestThread tt = new TestThread();
    Thread t1 =  new Thread(tt,"thread1");
    Thread t2 =  new Thread(tt,"thread2");

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 68935

Thread t1 =  new Thread(new TestThread(),"thread1");
Thread t2 =  new Thread(new TestThread(),"thread2");

You are creating two different instances of TestThread and

private int c=0;

is an instance variable(not a class variable). So it is expected for c to be 1 after run() is executed for each Thread.

Upvotes: 0

sakura
sakura

Reputation: 2279

You have created two thread objects.

    Thread t1 =  new Thread(new TestThread(),"thread1");
    Thread t2 =  new Thread(new TestThread(),"thread2");

And each thread object has its own copy of c as its not class level variable. Its instance variable.

So, it will not give you a value 2

Upvotes: 1

Related Questions