【原】使用和不使用ThreadLocal的对比示例

“ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本

 

对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式。前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响”

 

本示例如果不使用ThreadLocal,static的变量会被三个线程一同操作最后三个线程操作后,最后的值为9.

 

使用ThreadLocal后,每个线程有一个自己的static变量,打印出来是三个线程的static变量会变成3.

 

 

 

public class ThreadLocalDemo {
	private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {
		// 覆盖初始化方法
		public Integer initialValue() {
			return 0;
		}
	};

	// 下一个序列号
	public int getNextNum() {
		seqNum.set(seqNum.get() + 1);
		return seqNum.get();
	}
	private static int test;
	// 下一个序列号
	public int getNextNumTest() {
		test++;
		return test;
	}
	
	private static class TestClient extends Thread {
		private ThreadLocalDemo sn;
		
		

		public TestClient(ThreadLocalDemo sn,String threadName) {
			this.sn = sn;
			setName(threadName);
		}

		// 线程产生序列号
		public void run() {
			for (int i = 0; i < 3; i++) {
				System.out.println("thread[" + Thread.currentThread().getName()
						+ "] sn[" + sn.getNextNum() + "]");
			}
		}
		
		//没有使用ThreadLocal
		/*public void run() {
			for (int i = 0; i < 3; i++) {
				System.out.println("thread[" + Thread.currentThread().getName()
						+ "] sn[" + sn.getNextNumTest() + "]");
			}
		}*/
	}

	public static void main(String[] args) {
		ThreadLocalDemo sn = new ThreadLocalDemo();
		// 三个线程产生各自的序列号
		TestClient t1 = new TestClient(sn,"Thread t1");
		TestClient t2 = new TestClient(sn,"Thread t2");
		TestClient t3 = new TestClient(sn,"Thread t3");
		t1.start();
		t2.start();
		t3.start();
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值