Just run the code a lot of times and one of these lucky times you will be able to see the Thread Interference in action.
It is rare to observe in this case because its a small program and not much is happening.If you make multiple increment and decrement Threads, Thread Interference will be easier to observe.
class Counter {
private int c = 0;
public void increment() {c++;}
public void decrement() {c--;}
public int value() {
return c;
}
public static void main(String[] args) {
Counter x = new Counter();
Runnable r1 = new Runnable() {
@Override
public void run() {
x.increment();
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
x.decrement();
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
System.out.println(x.c);
}
}
Edit : I decided to add the multiple thread case , I couldn't resist
Edit 2 : This is a second edit.The multiple thread case since that was creating issues beyond the scope of this question I decided to remove it.previously I was making an array of threads and running them.Instead it will be better to show a thread that does a lot of increment and another that does a lot of decrement.
I have used Thread.Sleep() Causing The main thread to sleep which will make sure to print c after both threads are done operating on it.
class Counter {
private int c = 0;
public void increment() {
for (int i = 0; i < 10000; i++) {
c++;
}
}
public void decrement() {
for (int i = 0; i < 5000; i++) {
c--;
}
}
public int value() {
return c;
}
public static void main(String[] args) {
Counter x = new Counter();
Runnable r1 = new Runnable() {
@Override
public void run() {
x.increment();
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
x.decrement();
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(!(t1.isAlive() && t2.isAlive()))
System.out.println(x.c);//expected answer 5000
}
}
Note:Synchronized Increment/Decrement methods give the correct answer.Try yourself.