synchronized学习笔记

非静态方法锁定的是方法的调用者 这里锁定的是
静态方法锁定的是类

只要看锁定的资源的数量,当抢占的资源的数量只有一个时,线程就会排队取用;当资源数量有多个时,线程不用抢占,而是同时进行

package test;

import java.util.concurrent.TimeUnit;

public class Test {
//    public static void main(String[] args) {
//        Data data1 = new Data();
//        Data data2 = new Data();
//        //线程A
//        new Thread(()->{
//            data1.func1();
//        },"A").start();
//        //休眠一秒钟
//        try {
//            TimeUnit.SECONDS.sleep(1);//这个休眠是在主线程里面的
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        new Thread(()->{
//            data2.func2();
//        },"B").start();
//    }

    public static void main(String[] args) {
        Data2 data2 = new Data2();
        //开启了五个线程
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
//                Integer num = new Integer(1); //有五个厕所
//                Integer num = 1; 只有一个厕所,用到包装类的常量池 -128~127,超过这个范围就不使用常量池了
                //String str = new String("hello) 用的是堆内存的,String str = "hello"用的是常量池的,常量池只有一个

                Integer num = 127;
                data2.func(num);
            }).start();
        }
    }
}
class Data{
    //非静态方法锁定的是方法的调用者 这里锁定的是data
    //静态方法锁定的是类
    public synchronized static void func1(){
        try {
            TimeUnit.SECONDS.sleep(3);//休眠三秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("1....");
    }
    public static void func2(){
        System.out.println("2....");
    }
}

class Data2{
    public void func(Integer num){
//        Integer num = 1;
        Integer num1 =1;
        Integer num2 =1;
        synchronized (num2){//this指的是当前的Data2实例化对象
            num2++;
            System.out.println("start...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("end..");
        }
    }
}

 

 
posted @ 2021-05-20 09:15  MyNorth  阅读(36)  评论(0)    收藏  举报