Java — ThreadLocal | Code Factory

package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadLocalTest {
public static void main(String... args) {
ThreadLocal tl = new ThreadLocal();
System.out.println(tl.get()); // null
tl.set("Code");
System.out.println(tl.get()); // Code
tl.remove();
System.out.println(tl.get()); // null
}
}
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadLocalTest {
public static void main(String... args) {
ThreadLocal tl = new ThreadLocal() {
public Object initialValue() {
return "Hello";
}
};
System.out.println(tl.get()); // Hello
tl.set("Code");
System.out.println(tl.get()); // Code
tl.remove();
System.out.println(tl.get()); // Hello
}
}
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadLocalTest {
public static void main(String... args) {
CustomerThread c1 = new CustomerThread("Customer 1");
CustomerThread c2 = new CustomerThread("Customer 2");
CustomerThread c3 = new CustomerThread("Customer 3");
CustomerThread c4 = new CustomerThread("Customer 4");
c1.start();
c2.start();
c3.start();
c4.start();
}
}
class CustomerThread extends Thread {
static Integer custId = 0;

private static ThreadLocal tl = new ThreadLocal() {
protected Integer initialValue() {
// synchronized(this) { // #1
return ++custId;
// } // #2
}
};

CustomerThread(String name) {
super(name);
}

public void run() {
System.out.println(Thread.currentThread().getName() + " customer id : " + tl.get());
}
}
Customer 4 customer id : 3
Customer 2 customer id : 2
Customer 3 customer id : 4
Customer 1 customer id : 1
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadLocalTest {
public static void main(String... args) {
ParentThread pt = new ParentThread();
pt.start();
}
}
class ParentThread extends Thread {
public static InheritableThreadLocal l = new InheritableThreadLocal() {
public Object childValue(Object p) {
return "Child";
}
};

public void run() {
l.set("Parent");
System.out.println("Parent thread value : " + l.get());
ChildThread ct = new ChildThread();
ct.start();
}
}
class ChildThread extends Thread {
public void run() {
System.out.println("Child thread value : " + ParentThread.l.get());
}
}
Parent thread value : Parent
Child thread value : Child
Parent thread value : Parent
Child thread value : null
Parent thread value : Parent
Child thread value : Parent

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store