Reputation: 107
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
Reputation: 350
Each TestThread object has its own copy of c, so each will be incremented only once.
Upvotes: 1
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
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
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