Java并发编程笔记06 线程安全的单例

/*内部类实现单例,线程安全*/
public class Singleton {
	
	private Singleton() {}
	
	private static class InnerSingleton {
		private static Singleton sg = new Singleton();
	}
	
	public static Singleton getInstance(){
		return InnerSingleton.sg;
	}
}
package com.bjsxt.thread.sync010;

public class DubbleSingleton {
	
	private static DubbleSingleton instanse;
	
	public static DubbleSingleton getInstanse(){
		try {
			//模拟初始化的准备时间
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		synchronized (DubbleSingleton.class) {
			if(instanse == null) {
				instanse = new DubbleSingleton();
			}
		}
		return instanse;
	}
	
	public static void main(String[] args) {
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(DubbleSingleton.getInstanse().hashCode());
			}
		},"t1");
		
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(DubbleSingleton.getInstanse().hashCode());
			}
		},"t2");
		
		Thread t3 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(DubbleSingleton.getInstanse().hashCode());
			}
		},"t3");
		t1.start();
		t2.start();
		t3.start();
	}
}
public class ThreadLocalTest {
	//虽然变量是static的,但是ThreadLocal声明仅在当前进程中有效
	public static ThreadLocal<String> th = new ThreadLocal<String>();

	public void getTh() {
		System.out.println("当前线程"+Thread.currentThread().getName()+" | " + th.get());
	}

	public void setTh(String value) {
		th.set(value);
	}
	
	public static void main(String[] args) {
		//同一个对象里的同一个th属性
		final ThreadLocalTest ol = new ThreadLocalTest();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				ol.setTh("aaa");	
				ol.getTh();
			}
		},"t1");
		
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				ol.setTh("bbb");
				ol.getTh();
			}
		},"t2");
		
		t1.start();
		t2.start();
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/guchunchao/article/details/81636085