[英]Java's ReentrantLock is not working as expected
The question is simple, I just expect to see the demo.i to be 70000 since I have 7 threads and using a Lock, or it will be less than 70000 问题很简单,我只希望看到demo.i为70000,因为我有7个线程并使用Lock,或者它将小于70000
public class Sy {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Demo demo = new Demo();
Thread[] threads = new Thread[7];
for(int i=0;i<threads.length;i++) {
int finalI = i;
Thread thread = new Thread(() -> {
System.out.println("Thread " + finalI + " started!");
for(int j=0;j<10000;j++){
lock.lock();
demo.i++;
lock.unlock();
}
System.out.println("Thread " + finalI + " ended!");
});
threads[i] = thread;
thread.start();
}
System.err.println(demo.i);
}
}
class Demo {
public int i = 0;
}
You need to wait for the threads to finish before printing: 您需要在打印前等待线程完成:
for (Thread thread : threads) {
thread.join();
}
The threads need to finish 线程需要完成
Try this: 尝试这个:
public class Sy {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Demo demo = new Demo();
Thread[] threads = new Thread[7];
for(int i=0;i<threads.length;i++) {
int finalI = i;
Thread thread = new Thread(() -> {
System.out.println("Thread " + finalI + " started!");
for(int j=0;j<10000;j++){
lock.lock();
demo.i++;
lock.unlock();
}
System.out.println("Thread " + finalI + " ended!");
});
threads[i] = thread;
thread.start();
}
for(int i=0;i<threads.length;i++) {
try {
threads[i].join();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(demo.i);
}
}
class Demo {
public int i = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.