小编san*_*n A的帖子

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

我正在尝试使用关键字"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(); …
Run Code Online (Sandbox Code Playgroud)

java multithreading

1
推荐指数
1
解决办法
72
查看次数

标签 统计

java ×1

multithreading ×1