I have set the value of the flag, but the result is not 'add' and 'sub' alternates. Why? When I look at the result, it has executed twice the 'sub' method. But when the 'sub' method ended, the value of the flag will be set 'false'. But as a result, it printed "subxxxxx" twice continuously.
class Resource {
private boolean flag = true;
private int num = 0;
// At here I have declared an add()
public synchronized void add() throws InterruptedException {
if (this.flag == false) {
super.wait();
}
Thread.sleep(100);
this.num++;
System.out.println("addition:"+Thread.currentThread().getName() + this.num);
this.flag = false;
super.notifyAll();
}
// At here I have declared an sub()
public synchronized void sub() throws InterruptedException {
if (this.flag == true) {
super.wait();
}
Thread.sleep(200);
this.num--;
System.out.println("subtraction:"+Thread.currentThread().getName() + this.num);
this.flag = true;
super.notifyAll();
}
}
/*
* I will test it with multiple threads. For example:
*new Thread(ad, "add").start();
*new Thread(ad, "add").start();
*new Thread(sub, "sub").start();
*new Thread(sub, "sub").start();
*When threads start. it will execute alternately. For example:
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
But the result is like this:
Thread add:0
Thread sub:-1
Thread sub:-2
Thread add:-1
Thread sub:-3
Thread sub:-4
Why?Why?Why?
*/
new Thread(ad, "add").start();
new Thread(ad, "add").start();
new Thread(sub, "sub").start();
new Thread(sub, "sub").start();
}
}