public class jk {
static volatile int num=0;
static Object lock=new Object();
public static void main(String[] args) {
Runnable task1 = new Task1();
Runnable task2 = new Task2();
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(task1);
executorService.execute(task2);
System.out.println("oo");
}
static class Task1 implements Runnable{
@Override
public void run() {
while (num<100){
synchronized (lock){
if(num%2 == 0){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ num++);
lock.notifyAll();
}
}
}
}
static class Task2 implements Runnable{
@Override
public void run() {
while (num<100){
synchronized (lock){
if(num%2 != 0){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ num++);
lock.notifyAll();
}
}
}
}
}