示例:
package com.threadlocal的使用;
public class ThreadLocalTest {
//ThreadLocal<String> tl = new ThreadLocal<String>();
private static int a=0;
private synchronized static void incr() {
for (int i=0; i<5; i++){
try {
Thread.sleep(1000);
a++;
System.out.println(a);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
incr();
}
},"t1");
t1.start();
//主线程阻塞,一直等到t1线程运行结束后,主线程继续运行
t1.join();
System.out.println(a);
}
}