簡體   English   中英

Java的ReentrantLock沒有按預期工作

[英]Java's ReentrantLock is not working as expected

問題很簡單,我只希望看到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;

}

您需要在打印前等待線程完成:

for (Thread thread : threads) {
    thread.join();
}

線程需要完成

嘗試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM