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()方法。如果我是狼人,请纠正我。
答案 0 :(得分: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(")");
}
}
}