ThreadLocal



https://www.cnblogs.com/dolphin0520/p/3920407.html


public class UnsafeTask implements Runnable {
	private Date startDate;
	@Override
	public void run() {
		startDate = new Date();
		System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(), startDate);
		try {
			TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(), startDate);
	}
}

第一种,同一个Runnable对象时

public class Core {
	public static void main(String[] args) {
		UnsafeTask task=new UnsafeTask(); 
		 for (int i=0; i<10; i++){
//		UnsafeTask task=new UnsafeTask();
		Thread thread=new Thread(task);
		thread.start();
		try { TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
		e.printStackTrace();
		}
		}
	}
}

你会发现Thread Finished:的时间是相同的。

	public static void main(String[] args) {
//		UnsafeTask task=new UnsafeTask(); 
		 for (int i=0; i<10; i++){
		UnsafeTask task=new UnsafeTask();
		Thread thread=new Thread(task);
		thread.start();
		try { TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
		e.printStackTrace();
		}
		}
	}
此种情况每次都是新创建的Runnable对象,不存在上面的问题。

使用Threadlocal的方式

public class UnsafeTask implements Runnable {
	// private Date startDate;
	private static ThreadLocal<Date> startDate = new ThreadLocal<Date>() {
		protected Date initialValue() {
			return new Date();
		}
	};
	@Override
	public void run() {
		System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(), startDate.get());
		try {
			TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10));
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(), startDate.get());
	}
}

1


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值