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

本文介绍了两种实现线程安全单例模式的方法:一种是利用内部类实现懒汉式单例,另一种是双重检查锁定模式。同时,还探讨了如何使用ThreadLocal来为每个线程提供独立的变量副本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*内部类实现单例,线程安全*/
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();
	}
	
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值