Thoughts on synchronized blocked threads under multithreading after the interview

Not much nonsense, the code starts

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();;
        }
    }


}

to sum up:

  • Synchronized on ordinary methods will lock the call of the same object
  • Synchronized on static methods will be locked
  • synchronized (this) The role of the synchronized block is the same as that of the ordinary method, it will lock the call of the same object
  • synchronized (xxx.class) The role of the synchronized block is the same as on the static method, it will be locked

Guess you like

Origin blog.csdn.net/weixin_43957211/article/details/109361089