Created
January 10, 2018 06:45
-
-
Save fankay/5dc251a51f379b1331d2af559fdfd838 to your computer and use it in GitHub Desktop.
演示ThreadLocal的使用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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