我创建了一个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...