Reputation: 518
I did some research but I couldn't find right answer I guess.
public class MultiThreadTwo
{
private int count = 0;
public synchronized void increment() // I synchronized it here
{
count++;
}
public static void main (String [] args)
{
MultiThreadTwo app = new MultiThreadTwo();
app.doWork();
}
public void doWork()
{
Thread t1 = new Thread(new Runnable() {
public void run(){
for (int i=0;i<100;i++ )
{
increment(); // increments
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run()
{
for (int i=0;i<100;i++ )
{
increment(); // increments
}
}
});
t1.start();
t2.start();
System.out.println("Count is : "+count);
try
{
t1.join(); // wait for completes
t2.join(); // wait for completes
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
My output always diffrent like 200,182,171,65,140. How can I fix this I know I can check the value of count and if it is not the value I expected I can call the run again and again but It doesn't help me at all. synchronized keyword shouldn't fix that situation ?
What am I missing ?
Solution : Printing count after join fixed my problem.
Upvotes: 1
Views: 296
Reputation: 18586
If you join the threads before priniting the result and make count volatile, you will always get 200.
Eventhough volatile does not harm here, it is not necessary. The accesses to count from t1 and t2 work properly because increment method is synchronized on the same object and calling join on a thread creates a happens-before relationship. Thus, the main thread is guaranteed to see a correct value of count even without volatile, too.
Upvotes: 7