Java线程锁synchronized关键字

  • 作用于代码块,锁为对象。
  • 作用于静态函数,锁为静态函数所在的类。
  • 作用于非静态函数,锁为该函数所在的对象。
  • 谁先拿到锁,谁可暂时独享锁中逻辑。

1. 作用于方法

public class Test {
    public static void main(String[] args){
        Test test = new Test();
        new Thread(() -> test.setString("thread1\n")).start();
        new Thread(() -> test.setString("thread2\n")).start();
    }

    private synchronized void setString(String s){
        System.out.print(s);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

结果 thread2 推迟打印。

2. 作用于代码块

public class Test {
    public static void main(String[] args){
        Test test = new Test();
        new Thread(() -> test.setString("thread1\n")).start();
        new Thread(() -> test.setString("thread2\n")).start();
    }

    private void setString(String s){
        System.out.print(s);
        synchronized (Test.class){
            System.out.print("阻塞"+s);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

结果 阻塞thread2 推迟打印。

你可能感兴趣的:(Java基础)