package com.bj.thread;
import java.text.SimpleDateFormat;
public class TestThreadLocal implements Runnable {
// SimpleDateFormat is not thread-safe, so give one to each thread
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
@Override
public void run() {
System.out.println("Thread Name=" + Thread.currentThread().getName() +",formatter=" + formatter.get().toPattern() +",Start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
formatter.set(new SimpleDateFormat());
System.out.println("Thread Name=" + Thread.currentThread().getName() +",formatter=" + formatter.get().toPattern() + ",End");
}
public static void main(String[] args) {
TestThreadLocal threadLocal = new TestThreadLocal();
Thread thread = new Thread(threadLocal, "ThreadLocalName");
thread.start();
}
import java.text.SimpleDateFormat;
public class TestThreadLocal implements Runnable {
// SimpleDateFormat is not thread-safe, so give one to each thread
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
@Override
public void run() {
System.out.println("Thread Name=" + Thread.currentThread().getName() +",formatter=" + formatter.get().toPattern() +",Start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
formatter.set(new SimpleDateFormat());
System.out.println("Thread Name=" + Thread.currentThread().getName() +",formatter=" + formatter.get().toPattern() + ",End");
}
public static void main(String[] args) {
TestThreadLocal threadLocal = new TestThreadLocal();
Thread thread = new Thread(threadLocal, "ThreadLocalName");
thread.start();
}
}
来源:http://www.journaldev.com/1076/java-threadlocal-example-to-create-thread-local-variables