面试后的对多线程下同步synchronized阻塞线程的思考

本文探讨了Java中synchronized关键字在不同场景下的应用,包括普通方法、静态方法以及同步代码块,详细解释了它们如何实现线程同步并阻止线程阻塞。

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

废话不多说,代码走起

package com.zhku.thread;

public class TestThread {

    //阻塞
    public synchronized static void test() throws InterruptedException {
        for (int i=0; i<100; i++) {
            Thread.sleep(1000);
            System.out.println(i);
        }
    }
    //阻塞
    public static void test1() throws InterruptedException {
        synchronized (TestThread.class) {
            for (int i = 0; i < 100; i++) {
                Thread.sleep(1000);
                System.out.println(i);
            }
        }
    }
    //阻塞
    public void test2() throws InterruptedException {
        synchronized (TestThread.class) {
            for (int i = 0; i < 100; i++) {
                Thread.sleep(1000);
                System.out.println(i);
            }
        }
    }
    //相同对象阻塞,对象不相同不阻塞
    public void test3() throws InterruptedException {
        synchronized (this) {
            for (int i = 0; i < 100; i++) {
                Thread.sleep(1000);
                System.out.println(i);
            }
        }
    }

    //相同对象阻塞,对象不相同不阻塞
    public synchronized void test4() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            Thread.sleep(1000);
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
//        TestThread thread = new TestThread(); 在外面定义,每个线程的对象相同
        TestThread thread = new TestThread();
        for (int i=0; i<3; i++) {
            new Thread(()->{
                try {
//                    new TestThread().test();在循环里,每个线程的对象不相同
                    thread.test();//现在是同一个对象调用
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }).start();;
        }
    }


}

总结:

  • synchronized在普通方法上,会锁住同一对象的调用
  • synchronized在静态方法上,会锁住
  • synchronized (this)同步块的作用跟在普通方法上一样,都会锁住同一对象的调用
  • synchronized (xxx.class)同步块的作用跟在静态方法上一样,都会锁住
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值