public class LockSupport_Main {
private static Thread a, b, c;
public static void main(String[] args) {
a = new Thread(() -> {
for (int i = 0; i < 10; i++) {
LockSupport.park();
System.out.println("A");
LockSupport.unpark(b);
}
});
b = new Thread(() -> {
for (int i = 0; i < 10; i++) {
LockSupport.park();
System.out.println("B");
LockSupport.unpark(c);
}
});
c = new Thread(() -> {
for (int i = 0; i < 10; i++) {
LockSupport.park();
System.out.println("C");
LockSupport.unpark(a);
}
});
a.start();
b.start();
c.start();
LockSupport.unpark(a);
}
}
synchronized + wait()/notifyAll() + while(标志位)方法
public class Synchronized_Main {
private static final Object lock = new Object();
private static final boolean[] run = {true, false, false};
public static void main(String[] args) {
Thread a = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (!run[0]) lock.wait();
System.out.println("A");
run[0] = false;
run[1] = true;
lock.notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread b = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (!run[1]) lock.wait();
System.out.println("B");
run[1] = false;
run[2] = true;
lock.notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread c = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (!run[2]) lock.wait();
System.out.println("C");
run[2] = false;
run[0] = true;
lock.notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
a.start();
b.start();
c.start();
}
}