线程之wait和sleep的对比

1.概述

wait用于线程之间的通信,sleep用于让线程阻塞一段时间;

2.对比

1. wait 需要搭配 synchronized 使用. sleep 不需要.

2. wait 是 Object 的方法, sleep 是 Thread 的静态方法

3.单例模式

//Singleton单例,饿汉模式的单例模式的实现
//此处保证Singleton这个类只能创建出一个实例,
class Singleton {//在此处,先把这个实例给创建出来private static Singleton instance = new Singleton();
    //需要使用唯一实例,统一通过Singleton.getInstance()方式来获取public static Singleton getInstance(){
        return instance;
    }
    //为了避免Singleton不小心复制出多份来。//把构造方法设为private,在类外面,就无法通过new的方式来创建这个Singleton实例了;private Singleton() {}
}
public class ThreadDemo18 {public static void main(String[] args) {
         Singleton  s = Singleton.getInstance();
         Singleton s2 = Singleton.getInstance();
        //Singleton s3 =new Singleton();//结果为true,代码两个引用指向同一个
        System.out.println(s == s2);
    }
}

//懒汉单例模式
class SingletonLazy{
    private static SingletonLazy instance=null;
    public static SingletonLazy getInstance(){
        //值为空进行加锁,不为空不加锁if(instance == null){
            synchronized (SingletonLazy.class) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }

            }
        }
        return instance;
    }
    private SingletonLazy(){}
}
public class ThreadDemo20 {
    public static void main(String[] args) {
        SingletonLazy s = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s == s2);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值