Java線程:線程的同步

來源:互聯網
上載者:User

一、同步問題提出

線程的同步是為了防止多個線程訪問一個資料對象時,對資料造成的破壞。

例如:兩個線程ThreadA、ThreadB都操作同一個對象Foo對象,並修改Foo對 象上的資料。

public class Foo {
    private int x = 100;

    public int getX() {
        return x;
    }

    public int fix(int y) {
        x = x - y;
        return x;
    }
}

public class MyRunnable implements Runnable {
    private Foo foo = new Foo();

    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread ta = new Thread(r, "Thread-A");
        Thread tb = new Thread(r, "Thread-B");
        ta.start();
        tb.start();
    }

    public void run() {
        for (int i = 0; i < 3; i++) {
            this.fix(30);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread ().getName() + " : 當前foo對象的x值= " + foo.getX());
        }
    }

    public int fix(int y) {
        return foo.fix(y);
    }
}

運行結果:Thread-A : 當前foo對象的x值= 40
Thread-B : 當前foo對象的x值= 40
Thread-B : 當前foo對象的x值= -20
Thread-A : 當前foo對象的x值= -50
Thread-A : 當前foo對象的x值= -80
Thread-B : 當前foo對象的x值= -80

Process finished with exit code 0

從結果發現,這樣的輸出值明顯是不合理的。原因是兩個線程不加控制的訪 問Foo對象並修改其資料所致。

如果要保持結果的合理性,只需要達到一個目的,就是將對Foo的訪問加以限 制,每次只能有一個線程在訪問。這樣就能保證Foo對象中資料的合理性了。

在具體的Java代碼中需要完成一下兩個操作:

把競爭訪問的資源類Foo變數x標識為private;

同步哪些修改變數的代碼,使用synchronized關鍵字同步方法或代碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.