使用乐观锁+Thread.yield实现
package com.gavin;
import org.junit.jupiter.api.Test;
import java.util.concurrent.Semaphore;
public class LockTest {
private static final String strs = "HHOOHHOHOHHH";
private volatile int hNum = 0;
@Test
public void test() throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
for (char ch : strs.toCharArray()
) {
if (ch != 'H') {
continue;
}
System.out.println("线程:" + Thread.currentThread().getName() + ch);
hNum++;
while (hNum == 2) {
Thread.yield();
}
}
} catch (Exception e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
for (char ch : strs.toCharArray()) {
if (ch != 'O') {
continue;
}
System.out.println("线程" + Thread.currentThread().getName() + ch);
while (hNum != 2) {
Thread.yield();
}
hNum = 0;
}
} catch (Exception e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}