---
title: "java实现用单例模式返回一个线程安全的实例"
author: "smallsilver"
date: "2013-02-17T10:21:48Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-02-17T10:21:48Z"
id: 1781604
url: "https://wangde.iteye.com/blog/1781604"
---

直接上代码！

```java

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();
		}
	}
	
}

```