使用Lock可以使多线程数据安全
多线程安全问题:
package com.mock;
import org.junit.jupiter.api.Test;
public class TestLock {
@Test
public void test() throws InterruptedException {
ThreadLock tl = new ThreadLock();
new Thread(tl).start();
new Thread(tl).start();
new Thread(tl).start();
Thread.sleep(10000);
}
}
class ThreadLock implements Runnable {
private int i = 100;
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i > 0) {
System.out.println(Thread.currentThread().getName() + "--" + i--);
}
}
}
}
Thread-1--71
Thread-2--70
Thread-1--70
Thread-3--70
Thread-1--69
Thread-3--68
Thread-2--68
Thread-1--66
Thread-2--65
Thread-3--67
会出现脏读问题
加锁Lock解决如下:
class ThreadLock implements Runnable {
private int i = 100;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
lock.lock();
try {
Thread.sleep(500);
if (i > 0) {
System.out.println(Thread.currentThread().getName() + "--" + i--);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}