以下是Thread输入同步块,等待5秒然后退出的代码。 我同时启动了两个Thread实例。
预期其中一个线程将拥有对同步对象的锁定,而另一个将等待。 5秒后,当锁所有者退出时,将执行等待线程。
但是,实际上,两个线程同时执行同步块,并且同时退出。
预期产量:
Thread-X received the lock.
Thread-X exiting...
Thread-Y received the lock.
Thread-Y exiting...
实际输出:
Thread-X received the lock.
Thread-Y received the lock.
Thread-X exiting...
Thread-Y 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) {}
}
}
}