标签:[] 共享 简单方法 ring ble start extend over style
这是一个简单的面试题:
写一个简单的单例和多线程结合的例子;
代码:
单例代码:
public class Singleton { private int i = 0; //在类内部实例化单例, 将会在虚拟机启动加载类的时候加载该静态实例 private static Singleton singleton = new Singleton(); //自由化构造函数,以确保不会被外部类实例化 private Singleton() { System.out.println("初始化单例!"); } //获取该类内部静态实例方法 public static Singleton getSingleton () { return singleton; } public int getI() { return i; } public void setI(int i) { this.i = i; } }
线程继承类:
public class MyThread extends Thread { private Singleton singleton; //构造方法 MyThread (Singleton singleton) { this.singleton = singleton; System.out.println("初始化线程!"); } @Override public void run() { super.run(); singleton.setI(singleton.getI() + 1); System.out.println(singleton.getI()); } }
测试类:
public class Run { public static void main (String[] args) { Singleton singleton = Singleton.getSingleton(); //生成线程实例-1 MyThread thread1 = new MyThread(singleton); //生成线程实例-2 MyThread thread2 = new MyThread(singleton); //生成线程实例-3 MyThread thread3 = new MyThread(singleton); //生成线程实例-4 MyThread thread4 = new MyThread(singleton); //启动线程-1 thread1.start(); //启动线程-2 thread2.start(); //启动线程-3 thread3.start(); //启动线程-4 thread4.start(); } }
测试类输出:
初始化单例! 初始化线程! 初始化线程! 初始化线程! 初始化线程! 1 2 3 4
分析 :
1. 这里看到单例只被实例化了一次, 这是单例模式的特性, 并且多个线程见共享着单例实例;
2. 继承Thread是多线程实现的简单方法之一, 但是因为Java是单继承, 所以如果是已经继承其它类的类, 那么就可以通过实现 Runnable接口来实现;
标签:[] 共享 简单方法 ring ble start extend over style
原文地址:https://www.cnblogs.com/kns2017/p/9388028.html