[线程]——线程同步与锁定2_synchronized

来源:互联网 发布:java报表 编辑:程序博客网 时间:2024/05/22 14:27
/** * 单例设计模式:确保一个类只有一个对象 * @author Administrator * */public class SynDemo02 {public static void main(String[] args) {JvmThread thread1=new JvmThread(200);JvmThread thread2=new JvmThread(600);thread1.start();thread2.start();}}class JvmThread extends Thread{private long time;public JvmThread() {}public JvmThread(long time) {this.time=time;}@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"---->"+Jvm.getInstance3(1000));}}/** * 设计模式 * 确保一个类只有一个对象 * 懒汉模式 double double checking * 1、构造器私有化,避免外部直接创建对象 * 2、声明一个私有的静态变量 * 3、创建一个对外的公共的静态方法访问改变量,如果变量没有对象,创建该对象 * @author Administrator * */class Jvm{//1、声明一个私有的静态变量private  static Jvm instance=null;//2、构造器私有化,避免外部直接创建对象private Jvm(){}//3、创建一个对外的公共的静态方法访问改变量,如果变量没有对象,创建该对象public static Jvm getInstance3(long time){//静态资源,只有一份!!!// 提高效率,提供已经存在对象的访问效率if (null==instance) {synchronized(Jvm.class){if (null==instance) {try {Thread.sleep(time);//延时,方法发生错误} catch (InterruptedException e) {e.printStackTrace();}instance=new Jvm();}}}return instance;}public static Jvm getInstance2(long time){//静态资源,只有一份!!!synchronized(Jvm.class){if (null==instance) {try {Thread.sleep(time);//延时,方法发生错误} catch (InterruptedException e) {e.printStackTrace();}instance=new Jvm();}return instance;}}public static Jvm getInstance1(long time){//静态资源,只有一份!!!if (null==instance) {try {Thread.sleep(time);//延时,方法发生错误} catch (InterruptedException e) {e.printStackTrace();}instance=new Jvm();}return instance;}}

0 0