簡體   English   中英

同步方法 - 這是如何工作的?

[英]Synchronized methods - how does this work?

我最近看到了一個例子。 我無法理解主線程和乘客線程如何一次保持在同步塊中?

public class bus 
{
    public static void main(String[] args) throws InterruptedException 
    {
        passenger p = new passenger();
        p.start();
        synchronized (p) 
        {
            System.out.println("passenger is waiting for the bus, i am in synchronised method");
            p.wait();
            System.out.println("passenger  got notification");
        }
        System.out.println("after "+p.total+" time");
    }
}

class passenger  extends Thread 
{
    int total = 0;

    public void run() 
    {
        synchronized (this) 
        { 
            System.out.println("wait ....  i am in synchronised method");
            for (int i = 0; i <= 1000; i++)
            total = total + i;
            System.out.println("passenger  is given  notification call");
            notify();
        }
    }
} 

這個程序的輸出是

passenger is waiting for the bus i am in synchronised method
wait ....  i am in synchronised method
passenger  is given  notification call
passenger  got notification
after 500500 time

這意味着當主線程打印“乘客正在等待總線時,我處於同步方法”時,它已經處於同步阻塞狀態並等待。 打印的下一個語句是“等待......我在同步方法中”,這意味着乘客線程也進入了同步塊。 請記住,兩個同步塊都具有相同的對象 - p作為塊對象。 這看起來很混亂,因為我理解當主線程進入synchronized(p)塊時,主線程必須阻塞對象p並且根據定義,沒有其他線程可以訪問或輸入對象p任何同步塊或方法!

主線程和乘客線程如何同時保持在同步塊中?

p.wait() 釋放 p上的鎖,直到線程重新喚醒為止,因此只要最多一個線程沒有等待,就可以在psynchronized任意數量的線程。

來自Object的javadoc

 public final void wait() throws InterruptedException 

當前線程必須擁有此對象的監視器。 線程釋放此監視器的所有權並等待,直到另一個線程通過調用notify方法或notifyAll方法通知等待此對象監視器的線程喚醒。 然后線程等待,直到它可以重新獲得監視器的所有權並繼續執行。

暫無
暫無

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

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