enter image description here
我想验证synchronized关键字!!但是结果和我预测的不一致!!我不明白为什么会发生死锁
private final ReentrantLock lock = new ReentrantLock(true);
private int atomicInteger = 0;
public void writer() {
dd();
}
public void reader() {
dd();
}
public synchronized void dd() {
atomicInteger++;
}
public void test() {
lock.lock();
atomicInteger = 0;
Thread writer = new Thread(this::writer);
Thread reader = new Thread(this::reader);
writer.start();
reader.start();
for (; ; ) {
if (atomicInteger == 2) {
lock.unlock();
System.out.println(Thread.currentThread().getName()+"Lock released!");
break;
}
}
}
@Test
public void volatileTest() {
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(this::test);
thread.setName("thread【" + i + "】");
thread.start();
}
for (; ; ) {
}
}
1条答案
按热度按时间ogq8wdun1#
我使用synchronized来确保atominIntger在被修改时会被更新到主存中!但是它似乎不起作用