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

    1. 单例模式恶汉式

    package com.ithuanyu;
    
    public class SingletonE {
    
    	static SingletonE singeltonE = new SingletonE();
    
    	private SingletonE() {
    
    	}
    
    	public static SingletonE getSingletonE() {
    		return singeltonE;
    	}
    
    }
    

    2.懒汉式

    public class Singleton {
    
    	private Singleton() {
    	}
    	//懒汉式
    	static Singleton singleton = null;
    	
    
    	public static Singleton getSingeton() {
    		if (singleton == null) {
    			synchronized (Singleton.class) {
    				if (singleton == null) {
    					singleton = new Singleton();
    				}
    			}
    		}
    		return singleton;
    	}
    
    	public static void main(String[] args) {
    		Thread t1 = new Thread(new Runnable() {
    
    			@Override
    			public void run() {
    				Singleton singeton = Singleton.getSingeton();
    				System.err.println(singeton);
    			}
    
    		});
    		Thread t2 = new Thread(new Runnable() {
    
    			@Override
    			public void run() {
    				Singleton singeton = Singleton.getSingeton();
    				System.err.println(singeton);
    			}
    
    		});
    		Thread t3 = new Thread(new Runnable() {
    
    			@Override
    			public void run() {
    				Singleton singeton = Singleton.getSingeton();
    				System.err.println(singeton);
    			}
    
    		});
    		Thread t4 = new Thread(new Runnable() {
    
    			@Override
    			public void run() {
    				Singleton singeton = Singleton.getSingeton();
    				System.err.println(singeton);
    			}
    
    		});
    		Thread t5 = new Thread(new Runnable() {
    
    			@Override
    			public void run() {
    				Singleton singeton = Singleton.getSingeton();
    				System.err.println(singeton);
    			}
    
    		});
    		t1.start();
    		t2.start();
    		t3.start();
    		t4.start();
    		t5.start();
    
    	}
    
    }
    

      

  • 相关阅读:
    Codeforces Round #296 (Div. 2B. Error Correct System
    实验十二 图的建立与遍历
    1561: (More) Multiplication
    1562: Fun House
    hdu 2203 亲和串
    hdu 3549Flow Problem
    poj 2182 Lost Cows
    poj 3468A Simple Problem with Integers
    hdu1698 Just a Hook
    栈和队列的面试题Java实现
  • 原文地址:https://www.cnblogs.com/liushisaonian/p/9692411.html
Copyright © 2011-2022 走看看