【发布时间】:2019-02-27 20:21:18
【问题描述】:
下面是Thread 进入同步块,等待 5 秒然后退出的代码。我同时启动了两个Thread 实例。
期望线程之一将拥有同步对象上的锁,而另一个将等待。 5秒后,当锁拥有者退出时,等待线程将执行。
但实际上,两个线程都在同时执行同步块并同时退出。
预期输出:
Thread-X <timeX> received the lock.
Thread-X <timeX+5s> exiting...
Thread-Y <timeY> received the lock.
Thread-Y <timeY+5s> exiting...
实际输出:
Thread-X <time> received the lock.
Thread-Y <time> received the lock.
Thread-X <time+5s> exiting...
Thread-Y <time+5s> exiting...
我错过了什么吗?
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test2 {
public static void main(String[] args) {
MyRunnable m = new MyRunnable();
Thread t = new Thread(m);
Thread t1 = new Thread(m);
t.start();
t1.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
synchronized (this) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " received the lock.");
wait(5000);
date = new Date(System.currentTimeMillis());
System.out.println(Thread.currentThread().getName() + " " + formatter.format(date) + " exiting...");
} catch(InterruptedException ie) {}
}
}
}
【问题讨论】:
-
无关:请停止使用
Date类。java.time包太棒了。
标签: java multithreading synchronized thread-synchronization