叨叨两句

马上要开始啦!

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()方法是抽象方法。

Wall_Breaker
2.1k 声望1.2k 粉丝

生死之间,就是我的跃迁之路,全程记录,欢迎见证