使用乐观锁+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();
}
}
最后
以上就是称心人生最近收集整理的关于乐观锁和悲观锁解决leetcode的1117题目H2O生成问题的全部内容,更多相关乐观锁和悲观锁解决leetcode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复