多线程同步块每次都给出随机答案

时间:2017-08-14 04:15:13

标签: java multithreading java-8 threadpool

我创建了一个JAVA prog来检查synchronized块的工作情况。但它每次都会给出随机答案。任何人都可以解释为什么它会像那样。

程序:

public class ThreadSyncex1 extends Thread {
  public static void main(String[] args) {
    call a=new call();
    call b=new call();
    a.start();
    b.start();
    try {
      a.join();
      b.join();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  } 
}

class call extends Thread {
  public void run() {
    System.out.println(System.currentTimeMillis());         
    synchronized(this)
    {
      try {  
        System.out.println(Thread.currentThread().getName());  
        System.out.println("Success...");
        Thread.sleep(500);
      } catch(Exception e){
        System.out.println(e);
      }              
    }
  }
}

提供输出:

1502683588129
1502683588129
Thread-1
Thread-0
Success...
Success...

1502683592249
1502683592249
Thread-1
Success...
Thread-0
Success...

0 个答案:

没有答案