Java的ReentrantLock无法正常工作

时间:2019-04-05 02:51:12

标签: java multithreading

问题很简单,我只希望看到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;

}

2 个答案:

答案 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;

}