簡體   English   中英

Java線程示例中的同步混淆

[英]Synchronization confusion in Java Thread Example

public class Mythread extends Thread{
    Parenthesis p = new Parenthesis();
    String s1;
    Mythread(String s){
        s1 = s;
    }
    public void run(){
        p.display(s1);
    }
    public static void main(String[] args) {
        Mythread t1 = new Mythread("Atul");
        Mythread t2 = new Mythread("Chauhan");
        Mythread t3 = new Mythread("Jaikant");
        t1.start();
        t2.start();
        t3.start();

    }

}

class Parenthesis{
    public void display(String str){
        synchronized (str) {
            System.out.print("("+str);  
            try {
                Thread.sleep(1000);
                //System.out.print("("+Thread.currentThread().getName());
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.print(")");
        }


}
}

我得到的輸出像(Atul(Chauhan(Jaikant)))。 根據我的知識,每個Thread的對象都有自己的Personhesis對象的副本,這就是為什么得到輸出(Atul(Chauhan(Jaikant)))。所以即使同步方法display()也不會產生像(Atul)(Chauhan)(Jaikant)的結果)。 因此,如果我想要所需的輸出,我必須制作同步靜態display()方法。 如果我知道,請糾正我。

如果你想要像(Atul)(Chauhan)(Jaikant)這樣的輸出,你需要所有線程在同一個對象上同步。

例:

class Parenthesis{
    static final String syncObject = "Whatever";

    public void display(String str){
        synchronized (syncObject) {
            System.out.print("("+str);  
            try {
                Thread.sleep(1000);
                //System.out.print("("+Thread.currentThread().getName());
            } catch (Exception e) {
                System.out.println(e);
            }
            System.out.print(")");
        }
    }
}

暫無
暫無

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

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