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

废话不多说,代码走起

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)同步块的作用跟在静态方法上一样,都会锁住

猜你喜欢

转载自blog.csdn.net/weixin_43957211/article/details/109361089