之前使用锁加wait和notify的方式来实现两个线程交替打印一个字符串,也可以考虑使用Volatile关键字来实现线程间的通信,代码如下:
private volatile boolean flag4Volatile = true;
private int index = 0;
@Test
public void testVolatile() throws InterruptedException {
var str = "我是个大帅逼";
var strs = str.split("");
Thread t1 = new Thread( () -> {
while (index < strs.length) {
if (flag4Volatile) {
log.info(Thread.currentThread().getName() + ": " + strs[index++]);
flag4Volatile = false;
}
}
});
Thread t2 = new Thread( () -> {
while (index < strs.length) {
if (!flag4Volatile) {
log.info(Thread.currentThread().getName() + ": " + strs[index++]);
flag4Volatile = true;
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
测试结果如下