簡體   English   中英

我已經開始學習線程同步。我寫了一些代碼。為什么有時同步塊不起作用?

[英]I have started learning synchronization in threading.I wrote some code.Why sometimes synchronized block doesn't work right?

我只是想用 2 個線程增加變量,但有時顯示值不正確。

public class SynchBlock {
public static void main(String[] args) throws InterruptedException {
        SynchBlock obj= new SynchBlock();
        obj.dowork();
}
    }

同步塊的方法

    private int count;
    public void call() {
        synchronized (this) {
            count++;
        }
    }

SynchBlock 方法運行線程

    public void dowork() throws InterruptedException {
        th1.start();
        th2.start();
        th1.join();
        th1.join();
        System.out.println(count);
    }

線程 class 1 只是增加計數值

    Thread th1 = new Thread(new Runnable() {

        public void run() {
            for (int i = 0; i < 10000; i++) {
                call();
            }
        }

    });

線程 class 2 只是增加計數值

    Thread th2 = new Thread(new Runnable() {

        public void run() {
            for (int i = 0; i < 10000; i++) {
                call();
            }
        }

    });

你不加入th2 您加入th1兩次,因此有時您會在th2完成之前打印count

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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