【发布时间】:2020-02-16 04:52:33
【问题描述】:
我尝试了使用同步、lock.lock() 和 lock.tryLock() 的线程竞赛程序,我发现使用同步和 lock.lock() 可以正常工作,但 lock.tryLock() 本身不是线程安全的。此方法无法获取锁,因此会产生意想不到的结果
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Resources resources = new Resources();
Thread userThread1 = new Increment(resources);
Thread userThread2 = new Decrement(resources);
userThread1.start();
userThread2.start();
userThread1.join();
userThread2.join();
System.out.println(resources.getCounter());
}
}
private static abstract class UserThread extends Thread {
protected Resources resources;
public UserThread(Resources resources) {
this.resources = resources;
}
}
private static class Increment extends UserThread {
public Increment(Resources resources) {
super(resources);
}
public void run() {
for (int i = 0; i < 10000; i++) {
resources.increemnt();
}
}
}
private static class Decrement extends UserThread {
public Decrement(Resources resources) {
super(resources);
}
public void run() {
for (int i = 0; i < 10000; i++) {
resources.decrement();
}
}
}
private static class Resources {
public ReentrantLock getLock() {
return lock;
}
private ReentrantLock lock = new ReentrantLock();
public int getCounter() {
return counter;
}
private int counter = 0;
public void increemnt() {
if (lock.tryLock()) {
try {
counter++;
} finally {
lock.unlock();
}
}
}
public void decrement() {
if (lock.tryLock()) {
try {
counter--;
} finally {
lock.unlock();
}
}
}
}
}
预期:0,0,0,0,0,0,0,0,0,0 实际输出:每次运行都是随机的
【问题讨论】:
标签: java multithreading concurrency java-threads reentrantlock