【222天】黑马程序员27天视频学习笔记【Day25-上】

本文介绍了单例设计模式的概念及三种实现方式,并对比了饿汉式与懒汉式的优劣。此外,还介绍了Java中Runtime类的使用方法及其特点,以及如何利用Timer类实现定时任务。

叨叨两句

马上要开始啦!

25-01:单例设计模式

单例设计模式是什么?

一个类,只能创建一个对象

三种实现方式——1(饿汉式)

package com.test.demo001.lll;

public class Demo016 {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }
}

class Singleton {
    
    private Singleton(){
        
    }
    
    private static Singleton s1 = new Singleton();
    
    public static Singleton getInstance() {
        return s1;
    }
    
}

三种实现方式——2(懒汉式)

package com.test.demo001.lll;

public class Demo016 {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }
}

class Singleton {
    
    private Singleton(){
        
    }
    
    private static Singleton s;
    
    public static Singleton getInstance() {
        if(s == null) {
            s = new Singleton();
        }
        return s;
    }
    
}

三种实现方式——3(使用final)

package com.test.demo001.lll;

public class Demo016 {
    public static void main(String[] args) {
        Singleton s1 = Singleton.s;
        Singleton s2 = Singleton.s;
        System.out.println(s1 == s2);
    }
}

class Singleton {
    
    private Singleton(){}
    
    public static final Singleton s = new Singleton();
}

优劣比较

  1. 饿汉式虽然使用的内存空间比懒汉式多,但是它使用的时间少,开发推荐。
  2. 在多线程访问时,饿汉式只会新建一个对象,但是懒汉式有可能新建多个对象。

25-02:Runtime

使用价值

可以使用指定的字符串命令

使用方法

  1. exec
package com.test.demo001.lll;

import java.io.IOException;

public class Demo016 {
    public static void main(String[] args) throws IOException {
        Runtime r = Runtime.getRuntime();
        r.exec("shutdown -a");
    }
}

特点

  1. 使用了单例设计模式

25-03:Timer

使用价值

  1. 一种计时器

使用方法

  1. schedule()【第一个参数是任务,第二个参数是运行时间】
package com.test.demo001.lll;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Demo016 {
    public static void main(String[] args) throws InterruptedException {
        Timer t = new Timer();
        t.schedule(new MyTimerTask(),new Date(117,8,15,16,52,50),3000); 
        while(true){
            Thread.sleep(1000);
            System.out.println(new Date());
        }
    }
} 

class MyTimerTask extends TimerTask {
    public void run(){
        System.out.println("起床了!!!");
    }
}

特点

  1. Date中的年要减去1900,月是0-11,日是1-31,小时是0-11,分是0-59,秒是0-59
  2. TimerTask是抽象类,其中的run()方法是抽象方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值