Java synchronized阻塞的同步队列现象分析

本文探讨Java中synchronized关键字导致的线程进入同步队列的现象,详细分析了线程如何从BLOCKED状态到尝试获取锁的过程。尽管线程请求同步的顺序是1-9,但实际获取锁的顺序却是9-1,揭示了锁释放和获取的非直观行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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...
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值