多线程(五)--单例和多线程

1.ThreadLocal的示例

public class ConnThreadLocal {
	public static ThreadLocal<String> th = new ThreadLocal<>();

	public static void setTh(String value) {
		th.set(value);
	}

	public static void getTh() {
		System.out.println(Thread.currentThread().getName() + ": " + th.get());
	}

	public static void main(String[] args) {
		final ConnThreadLocal ct = new ConnThreadLocal();
		Thread t1 = new Thread(() -> {
			ct.setTh("张三");
			ct.getTh();
		}, "t1");


		Thread t2 = new Thread(() -> {
			try {
				Thread.sleep(1000);
				ct.getTh();

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "t2");

		t1.start();
		t2.start();
	}
}

第二个线程获取全局变量的value时没有得到值。运行结果说明,ThreadLocal保存的是线程的局部变量。

2.单例,推荐

public class Singleton {

	private Singleton() {
	}

	private static class SingletonHolder {
		private static final Singleton INSTANCE = new Singleton();
	}

	public static final Singleton getInstance() {
		return SingletonHolder.INSTANCE;
	}
}

猜你喜欢

转载自blog.csdn.net/csdn_kenneth/article/details/82784173