I have a variable which is shared by two threads. The two threads will do some operations on it. I don\'t know why the result of sharedVar is different every time I execute
When you use synchronized
on non-static method, you use current object as monitor.
When you use synchronized
on static method, you use current object of class (ClassName.class
static field) as monitor.
In your case, you use synchronized
on Thread's object (2 different instances), so two different threads will modify your sharedVar
static field at same time.
You can fix it in different ways.
Move addOne
method to Main
and make it static
.
private static synchronized void addOne(int times)
{
for (int i = 0; i < times; ++i)
{
sharedVar++;
}
}
Or you can create class called SharedVar
with field private int var;
and method synchronized void addOne(int times)
and pass single instance of SharedVar
to your treads.
public static void main(String[] args)
{
SharedVar var = new SharedVar();
MyThread mt1 = new MyThread(var);
MyThread mt2 = new MyThread(var);
mt1.start();
mt2.start();
try
{
// wait for the threads
mt1.join();
mt2.join();
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
System.out.println(var.getVar()); // I expect this value to be 20000, but it's not
}
But if you need only one integer to be changed in multiple threads, you can use classes from java.til.concurrent.*
, like AtomicLong
or AtomicInteger
.