2014-02-13 64 views
0
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))))。據我所知,每個線程的對象都有自己的括號對象的副本,這就是爲什麼得到像(Atul(Chauhan(Jaikant)))的輸出的原因。所以即使同步方法display()也不會產生像(Atul)(Chauhan)(Jaikant )。所以,如果我想要所需的輸出,我必須做syncronized靜態顯示()方法。糾正我,如果我worng。Java中的同步混亂線程示例

+0

你還可分享所有3個線程之間的相同的括號實例(並顯示同步的方法,當然),如果你想避免的靜態方法。 – Fildor

+0

所以我上面解釋的是正確的@ Fildor –

+0

你可以按照你說的方式去做。但它不是最好的。其實有多種方法可以獲得理想的結果。說到同步,你應該儘可能簡單。正如彼得所說的:確保你真的需要多線程。 – Fildor

回答

2

如果你想輸出像(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(")"); 
     } 
    } 
} 
+2

+1你可以使用synchronized(Parent.class)。不需要額外的同步對象 – giorashc

+1

+1或不使用線程,只需使用循環。你應該只使用多個線程,比使用一個線程更簡單/更好。 –