public class Singleton {
public static void main(String[] args) throws InterruptedException {
for (int i=0; i<10; i++){
new Thread(new QueueThread()).start();
Thread.sleep(10);
}
}
static class QueueThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running...");
synchronized (QueueThread.class){
System.out.println(Thread.currentThread().getName() + " has got lock...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
运行结果:
Thread-0 is running...
Thread-0 has got lock...
Thread-1 is running...
Thread-2 is running...
Thread-3 is running...
Thread-4 is running...
Thread-5 is running...
Thread-6 is running...
Thread-7 is running...
Thread-8 is running...
Thread-9 is running...
Thread-9 has got lock...
Thread-8 has got lock...
Thread-7 has got lock...
Thread-6 has got lock...
Thread-5 has got lock...
Thread-4 has got lock...
Thread-3 has got lock...
Thread-2 has got lock...
Thread-1 has got lock...
Process finished with exit code 0
任意线程对同步块的访问,首先要获取其锁对象的监视器,,如果获取失败(当前锁被其他线程持有,并未释放),则该线程进入同步队列,线程的状态变成BLOCKED,当访问该锁对象的前驱(获得了锁的线程)释放了锁,则该释放操作会唤醒阻塞在同步队列中的线程,使其重新尝试对监视器的获取。
分析上述代码的的打印结果,可以知道,尝试请求同步块的线程次序依次是Thread 1-9,而后续成功获得锁的线程次序却是Thread 9-1,难道不是队列中排在前面的线程,先获取释放的锁吗??