前记
上一篇温习的是java中线程范围内的共享变量的map方式实现,这次来温习ThreadLocal方式
场景及代码
package com.web.thread;
import java.util.Random;
/*********************************************************************************
//* Copyright (C) 2015 Pingan (PA). All Rights Reserved.
//*
//* Filename: ThreadScopeShareData.java
//* Revision: 1.0
//* Author: <gao yunqi>
//* Created On: 2016年3月16日
//* Modified by:
//* Modified On:
//*
//* Description: <线程范围内的共享变量ThreadLocal>
/********************************************************************************/
public class ThreadLocalTest {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer> ();
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int data = new Random().nextInt();
threadLocal.set(data);
System.out.println(Thread.currentThread().getName() +
" has put data " + data);
new Step1().getData();
new Step2().getData();
}
}).start();
}
}
static class Step1{
public void getData(){
System.out.println("Step1 from " + Thread.currentThread().getName() +
" get data " + threadLocal.get());
}
}
static class Step2{
public void getData(){
System.out.println("Step2 from " + Thread.currentThread().getName() +
" get data " + threadLocal.get());
}
}
}
以上便是ThreadLocal实现的线程范围内的共享变量