使用wait() 和 nodify() 实现线程之间的切换。所以需要synchronized以及lock进行同步代码。因为俩个线程需要切换,必然需要一个标示flag决定线程是等待还是获得锁。
volatile 的特性
保证了不同线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。(实现可见性)
禁止进行指令重排序。(实现有序性)
volatile 只能保证对单次读/写的原子性。i++ 这种操作不能保证原子性。
实现代码:
package com.example.test_mysql;
public class TestAa {
private static volatile int flag = 0;
private static Object o = new Object();
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
for (int i =97;i<123;){
synchronized (o){
if (flag==1){
System.out.printf(""+(char)i);
flag=0;
i++;
o.notify();
}else {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread thread2 = new Thread(() -> {
for (int i =65;i<91;){
synchronized (o){
if (flag==0){
System.out.printf(""+(char)i);
flag=1;
i++;
o.notify();
}else {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
thread1.start();
thread2.start();
}
}