ITeye博客

java实现用单例模式返回一个线程安全的实例

smallsilver · 2013-02-17 10:21 · java · thread · 编程语言 · Markdown

直接上代码!


package thread;

/**
 * java实现用单例模式返回一个线程安全的实例
 * @author Administrator
 *
 */
public class GetSyncInstance {
	
	private static GetSyncInstance instance;
	private static int i;
	
	private static synchronized void initSyn(){
		if(instance==null)
			instance = new GetSyncInstance("123");
	}
	
	public static GetSyncInstance GetInstance(){
		if(instance==null){
			initSyn();
		}
		return instance;
	}
	
	public GetSyncInstance(){
	}
	public GetSyncInstance(String ss){
		i++;
		System.out.println("instance="+" "+i);
	}
	
	public static void main(String[] args) {
		//用两个线程同时调用测试,只返回:instance= 1
		Thread t = new th1();
		t.start();
		Thread t1 = new th1();
		t1.start();
	}
}
class th1 extends Thread{

	@Override
	public void run() {
		for(int i=0;i<10;i++){
			GetSyncInstance.GetInstance();
		}
	}
	
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。