同步的java线程错误的输出序列

同步的java线程错误的输出序列,java,multithreading,synchronization,Java,Multithreading,Synchronization,嘿,我试着跟着这个 这是我的密码 class First { public void display(String msg) { System.out.print("["+msg); try { Thread.sleep(1000); } catch (InterruptedException ex) {} System.out.println("]"); } }

嘿,我试着跟着这个

这是我的密码

class First {
     public void display(String msg)   
     {
         System.out.print("["+msg);
         try {
             Thread.sleep(1000);
         } catch (InterruptedException ex) {}
         System.out.println("]");
     }
}

class Second extends Thread{
    String msg;
    First fobj;

    Second(First fp,String str){
        msg=str;
        fobj=fp;
        start();
    }

    public void run(){
        synchronized(fobj){
            fobj.display(msg);
        }
    } 
}

public class Main {

    public static void main(String[] args) {
        // TODO code application logic here
        First f=new First();
        Second s1=new Second(f,"welcome");
        Second s2=new Second(f,"new");
        Second s3=new Second(f,"programmer");
    }

}
这是我的结果

run:
[welcome]
[programmer]
[new]
BUILD SUCCESSFUL (total time: 3 seconds)

我的代码怎么了?为什么结果不受新程序员欢迎?

所有线程几乎同时启动,并相互竞争以获得共享对象的锁

不能保证第二个线程在第三个线程之前请求锁。即使是这样,锁也是不公平的,因此不能保证等待锁的第一个线程会首先得到它

使用上面的代码,您可以得到的唯一保证是,一次只有一个线程能够执行synchronized方法