import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class KT {
int num = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void add() throws InterruptedException {
lock.lock();
while (num != 0) {
condition.await();
}
num++;
System.out.println(num);
condition.signalAll();
lock.unlock();
}
public void decrease() throws InterruptedException {
lock.lock();
while (num == 0) {
condition.await();
}
num--;
System.out.println(num);
condition.signalAll();
lock.unlock();
}
}
public class addAndDecrease {
static KT kt = new KT();
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
new Thread() {
public void run() {
try {
kt.add();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
for (int i = 0; i < 5; i++) {
new Thread() {
public void run() {
try {
kt.decrease();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
// TODO Auto-generated method stub
}
}