在线程中使用同步关键字,但结果不正确?

san*_*n A 1 java multithreading

我正在尝试使用关键字"synchronized",但结果不正确.我无法弄清楚为什么在第二个对象之前给出第三个对象的调用.

预期产出:

hello
synchronized
world
Run Code Online (Sandbox Code Playgroud)

输出 - 我得到了什么

hello
world
synchronized
Run Code Online (Sandbox Code Playgroud)

以下是我使用的代码:

class Callme{
 synchronized void call(String msg){
  System.out.print("["+msg);

 try{
Thread.sleep(1000);
 }catch(InterruptedException ie){}
   System.out.println("]");
     }  
      }


class Caller implements Runnable{
   String msg;
   Callme target;
   Thread t;
   public Caller(Callme targ, String s){
      target=targ;
      msg=s;
      t=new Thread(this);
      t.start();
    }

  public void run(){
  target.call(msg);
   } 

}
 class Synch{
 public static void main(String[] args){
    Callme target=new Callme();
    Caller c1=new Caller(target,"hello");
    Caller c2=new Caller(target,"Synchronized");
    Caller c3=new Caller(target,"world");

try{
   System.out.println("Waiting for the threads to end");
   c1.t.join();
   c2.t.join();
   c3.t.join();
   }catch(InterruptedException ie){} 

   }    
 }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

你正在开始三个主题.每个都会调用call相同的Callme,所以一次只执行一个线程call......但这并不意味着线程将按照启动它们的顺序执行.

想象一下,你开始一场跑步比赛,在赛道的一半,你有一个门,一次只能有一个人通过.你几乎在同一时间开始10个跑步者 - 你为什么期望跑步者以你开始时的顺序进入大门?

基本上,同步提供了排他性 - 它没有指定排序.