volatile 控制
public class ThreadPrint {
private static volatile int i = 0;
private static volatile boolean who = true;
public static void main(String[] args) {
new Thread(() -> {
while (true) {
if (who) {
// 出口
if (i == 100) {
who = !who;
break;
}
System.out.println("t1 = " + i);
i++;
who = !who;
}
}
}).start();
new Thread(() -> {
while (true) {
if (!who) {
if (i == 100) {
who = true;
break;
}
System.out.println("t2 - " + i);
i++;
who = !who;
}
}
}).start();
}
}
notify 机制
public class ThreadPrint {
private static volatile int i = 0;
private static Object lock = new Object();
public static void main(String[] args) {
new Thread(() -> {
synchronized(lock) {
while (true) {
if (i == 100) break;
System.out.println("t1 - " + i);
i++;
lock.notify();
try {
// 释放锁
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 通知另一线程结束
lock.notify();
}
}).start();
new Thread(() -> {
synchronized (lock) {
while (true) {
if (i == 100) break;
System.out.println("t2 - " + i);
i++;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 通知另一线程结束
lock.notify();
}
}).start();
}
}
网友评论