zoukankan      html  css  js  c++  java
  • java设计模式单例模式

    package Test;
    
    public class ThreadAndSingleton {
    
    	private ThreadAndSingleton() {
    	}
    
    	private static ThreadAndSingleton threadAndSingleton = null;
    
    	/**
    	 * 试试不加synchronized关键字,会出现两个实例的
    	 * @param sleepTime
    	 * @return
    	 */
    	public static synchronized ThreadAndSingleton getIntstance(int sleepTime) {
    		if (threadAndSingleton == null) {
    			try {
    				Thread.sleep(sleepTime);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			threadAndSingleton = new ThreadAndSingleton();
    		}
    		return threadAndSingleton;
    		
    	}
    
    	public static void main(String[] args) {
    		/**
    		 * 下面这就属于模型驱动模式
    		 */
    		Thread th1 = new Thread(new Runnable() {
    			@Override
    			public void run() {
    				System.out.println("th1:" + ThreadAndSingleton.getIntstance(1000));
    			}
    		});
    		Thread th2 = new Thread(new Runnable() {
    			@Override
    			public void run() {
    				System.out.println("th2:" + ThreadAndSingleton.getIntstance(0));
    			}
    		});
    		th1.start();
    		th2.start();
    	}
    }
    

      关于

    getIntstance方法被同步的说明:如果不同步,同事访问这个方法可能造成进入后等待,然后另一次访问开始了,结果造成两个实例,就不是单例模式了。
  • 相关阅读:
    ajax实例2
    分页显示中关于"序号"的问题
    <s:property value=""/> 怎么截取返回值的固定长度的字符串
    py 的 第 13 天
    py 的 第 10 天
    py 的 第 8 天
    py 的 第 9 天
    py 的 第 7 天
    这几日英文大汇
    python第五天
  • 原文地址:https://www.cnblogs.com/mrye/p/2499841.html
Copyright © 2011-2022 走看看