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中的同步混亂線程示例
你還可分享所有3個線程之間的相同的括號實例(並顯示同步的方法,當然),如果你想避免的靜態方法。 – Fildor
所以我上面解釋的是正確的@ Fildor –
你可以按照你說的方式去做。但它不是最好的。其實有多種方法可以獲得理想的結果。說到同步,你應該儘可能簡單。正如彼得所說的:確保你真的需要多線程。 – Fildor