在进入条件之前,我试图了解锁和多线程的工作原理。这是我目前正在测试的代码:
public class tester {
private static int count = 0;
public void incrementCount() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new testing());
Thread thread2 = new Thread(new testing());
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(count);
}
}
这是实现 Runnable 的部分:
public class testing implements Runnable {
Lock lock = new ReentrantLock();
tester in = new tester();
public void run() {
for (int i = 0; i < 1000; i++) {
lock.lock();
in.incrementCount();
lock.unlock();
}
}
}
我遇到的问题是,我试图在 main 方法的末尾打印出 2000,但即使我使用了锁,它也从未真正达到 2000。帮助将不胜感激!
最佳答案
even though I am using locks.
您正在为两个线程中的每一个使用单独的锁。
如果你想让锁在线程之间协调,它们都需要使用同一个锁实例。否则毫无意义。
改成类似的东西
class Testing implements Runnable {
private final Lock lock;
// pass in the lock to use via the constructor
// both threads need to receive the same lock
Testing(Lock lock){ this.lock = lock; }
public void run() {
for (int i = 0; i < 1000; i++) {
lock.lock();
Tester.incrementCount();
lock.unlock();
}
}
}
关于java - 多线程和锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096660/