一、使用volatile关键字实现
public class Print10 {
static volatile int i = 0;
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while(i < 20){
synchronized (Print10.class){
// 锁的是类锁,所以要释放类的锁
Print10.class.notify(); // 唤醒其他线程可以抢锁了
System.out.println(Thread.currentThread().getName() + "打印:"+ i++);
try {
Print10.class.wait(); // 让此线程等待,避免下次和其他线程抢锁
} catch (InterruptedException