Skip to content

Instantly share code, notes, and snippets.

@fankay
Created January 10, 2018 06:45
Show Gist options
  • Save fankay/5dc251a51f379b1331d2af559fdfd838 to your computer and use it in GitHub Desktop.
Save fankay/5dc251a51f379b1331d2af559fdfd838 to your computer and use it in GitHub Desktop.
演示ThreadLocal的使用
package com.kaishengit.ppt;
public class Test {
public static void main(String[] args) throws InterruptedException {
User user = new User();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
user.setName("Jcak");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1 name :" + user.getName());
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
user.setName("Rose");
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread2 name :" + user.getName());
}
});
thread.start();
thread2.start();
}
}
package com.kaishengit.ppt;
public class User {
private ThreadLocal<String> nameThreadLocal = new ThreadLocal<>();
public void setName(String name) {
nameThreadLocal.set(name);
}
public String getName() {
return nameThreadLocal.get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment