欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程-单例模式

程序员文章站 2022-07-12 20:35:16
...
单例模式


一、概念

饿汉模式、懒汉模式

二、示例

package com.study.current.thread.day02;

/**
 * 单例,多线程
 */
public class InnerSingleton {

	private static class Singletion{
		private static Singletion single = new Singletion();
	}
	
	public static Singletion getInstance(){
		return Singletion.single;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}



package com.study.current.thread.day02;

import java.util.DuplicateFormatFlagsException;

public class DoubleCheckDemo {

	private static DoubleCheckDemo dc ;
	
	public static DoubleCheckDemo getDc(){
		if(dc == null){
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (DoubleCheckDemo.class) {
				if(dc == null){
					dc = new DoubleCheckDemo();
				}
			}
		}
		return dc ;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Thread t1 = new Thread(new Runnable() {
			
			public void run() {
				System.out.println(DoubleCheckDemo.getDc().hashCode());
			}
		});
		
		Thread t2 = new Thread(new Runnable() {
			
			public void run() {
				System.out.println(DoubleCheckDemo.getDc().hashCode());
			}
		});
		
		t1.start();
		t2.start();
	}

}




相关标签: thread

上一篇: Volatile

下一篇: 单例设计模式