Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java线程示例中的同步混乱_Java_Multithreading - Fatal编程技术网

Java线程示例中的同步混乱

Java线程示例中的同步混乱,java,multithreading,Java,Multithreading,我得到的输出像(Atul(Chauhan(Jaikant)))。据我所知,每个线程的对象都有自己的括号对象副本,这就是为什么会得到类似(Atul(Chauhan(Jaikant))的输出。因此,即使同步display()方法也不会产生类似(Atul)(Chauhan)(Jaikant)的结果。所以,如果我想要所需的输出,我必须使用syncronizedstaticdisplay()方法。如果我在工作,请纠正我。如果您想要像(Atul)(Chauhan)(Jaikant)这样的输出,您需要所有线程

我得到的输出像(Atul(Chauhan(Jaikant)))。据我所知,每个线程的对象都有自己的括号对象副本,这就是为什么会得到类似(Atul(Chauhan(Jaikant))的输出。因此,即使同步display()方法也不会产生类似(Atul)(Chauhan)(Jaikant)的结果。所以,如果我想要所需的输出,我必须使用syncronizedstaticdisplay()方法。如果我在工作,请纠正我。

如果您想要像(Atul)(Chauhan)(Jaikant)这样的输出,您需要所有线程在同一对象上同步

例如:

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(")");
        }


}
}

如果您想避免使用静态方法,还可以在所有3个线程之间共享同一个圆括号实例(当然,还可以使display方法同步)correct@FildorYou我可以照你说的做。但这不是最好的。实际上,有多种方法可以达到预期的效果。说到同步,您应该尽可能简单。正如Peter正确地说的:确保你真的需要多线程。事实上,我的朋友问了我这个问题。这个问题在面试中被问到了,面试官告诉他解释程序和预期输出。-Fildor+1你可以使用synchronized(括号.class)。不需要额外的同步对象+1,或者不使用线程,只使用循环。仅当多线程比仅使用一个线程更简单/更好时,才应使用多线程。
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(")");
        }
    }
}