问题很简单,我只希望看到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;
}
答案 0 :(得分:0)
在打印之前,您需要等待线程完成:
for (Thread thread : threads) {
thread.join();
}
答案 1 :(得分:0)
线程需要完成
尝试一下:
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;
}