单例设计模式:保证类在内存中只有一个对象。
如何保证类在内存中只有一个对象呢?
单例写法两种:
//饿汉式
class Singleton {
    //1,私有构造函数
    private Singleton(){}
    //2,创建本类对象
    private static Singleton s = new Singleton();
    //3,对外提供公共的访问方法
    public static Singleton getInstance() {
        return s;
    }
    public static void print() {
        System.out.println("11111111111");
    }
}
//懒汉式,单例的延迟加载模式
class Singleton {
    //1,私有构造函数
    private Singleton(){}
    //2,创建本类对象
    private static Singleton s;
    //3,对外提供公共的访问方法
    public static Singleton getInstance() {
        if(s == null)
            //线程1,线程2
            s = new Singleton();
        return s;
    }
    public static void print() {
        System.out.println("11111111111");
    }
}
class Singleton {
    private Singleton() {}
    public static final Singleton s = new Singleton();//final是最终的意思,被final修饰的变量不可以被更改
}
Runtime r = Runtime.getRuntime();
//r.exec("shutdown -s -t 300");     //300秒后关机
r.exec("shutdown -a");              //取消关机
Timer类:计时器
public class Demo5_Timer {
    /**
     * @param args
     * 计时器
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        Timer t = new Timer();
        t.schedule(new MyTimerTask(), new Date(114,9,15,10,54,20),3000);
        while(true) {
            System.out.println(new Date());
            Thread.sleep(1000);
        }
    }
}
class MyTimerTask extends TimerTask {
    @Override
    public void run() {
        System.out.println("起床背英语单词");
    }
}
原文地址:http://blog.csdn.net/qq_16807471/article/details/42363635