我正在了解java中的锁,但我很难理解这个概念。这是一个带锁的 Java 代码示例
public class LockQ {
class Shared {
static int count = 0;
}
class LockExample implements Runnable {
Lock lock;
public LockExample(Lock lock) {
this.lock = lock;
}
@Override
public void run() {
lock.lock();
for (int i = 0; i < 5; i++) {
System.out.println("Working on count = " + Thread.currentThread().getName());
Shared.count++;
}
lock.unlock();
}
}
public static void main(String[] args) {
LockQ obj = new LockQ();
obj.demo();
}
public void demo() {
Lock lock = new ReentrantLock();
LockExample l1 = new LockExample(lock);
LockExample l2 = new LockExample(lock);
LockExample l3 = new LockExample(lock);
Thread t1 = new Thread(l1);
Thread t2 = new Thread(l2);
Thread t3 = new Thread(l3);
t1.start();
t2.start();
t3.start();
/*
try {
t2.join();
t3.join();
t1.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
*/
System.out.println("Final count value " + Shared.count);
}
}
这是一个示例输出
Working on count = Thread-0
Working on count = Thread-0
Working on count = Thread-0
Working on count = Thread-0
Working on count = Thread-0
Working on count = Thread-1
Working on count = Thread-1
Working on count = Thread-1
Working on count = Thread-1
Working on count = Thread-1
Working on count = Thread-2
Working on count = Thread-2
Working on count = Thread-2
Working on count = Thread-2
Working on count = Thread-2
Final count value 0
我的困惑是
为什么最后的计数值是0?它在循环内的所有打印语句之后被打印,这意味着所有三个线程都已完成执行。如果连接语句未注释,代码将按预期工作,我明白了
最终计数值15
最后
如果您不
.join()
线程,则不能保证它们在后续工作发生之前完成(.join()
等待线程退出后再继续)!
所以发生的情况是你的主程序运行,然后在等待线程退出时挂起,但由于它发生得非常快,你可能看不到效果