0%

JAVA-同步锁-synchronized

控制Java多线程环境下的线程同步

对象锁

synchronized修饰方法或者代码块

类锁

synchronized修饰静态方法或者代码块

方法锁(对象锁)

synchronized修饰方法,锁住的也是这个对象

示例

public class SynchronizeTest {
    static class S{
        String name;
        public void setName(String name) throws InterruptedException {
            synchronized (this) {
                System.out.println("..........");
                Thread.sleep(1000*5L);
                this.name = name;
            }
        }
        public void print(){
            synchronized (this){
                System.out.println(name);
            }
        }
        public synchronized void doSomething1(){
            System.out.println("doSomething1");
            try {
                Thread.sleep(1000*5L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        public synchronized void doSomething2(){
            System.out.println(name);
        }
    }
    public static void main(String[] args) throws Exception{
        S s = new S();
//        Thread t1 = new Thread(() -> {
//            try {
//                s.setName("hello");
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        });
//        t1.start();
//        Thread t2 = new Thread(() -> {
//                s.print();
//        });
//        t2.start();
//        t1.join();
//        t2.join();
        Thread t1 = new Thread(() -> {
             s.doSomething1();
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            s.doSomething2();
        });
        t2.start();
        t1.join();
        t2.join();

    }
}