Skip to content

Instantly share code, notes, and snippets.

@tomotaka
Created February 1, 2013 02:50
Show Gist options
  • Save tomotaka/4688796 to your computer and use it in GitHub Desktop.
Save tomotaka/4688796 to your computer and use it in GitHub Desktop.
using thread-local on Java.
import java.util.Random;
public class ThreadLocalTest implements Runnable {
public static final Random RAND = new Random();
public static int counter = 1;
public static class MyObject {
private final int n;
public MyObject(final int n) {
this.n = n;
}
public void init() {
System.out.println("object " + n + " is initialized");
}
public void work() {
System.out.println("object " + n + " is working now");
}
}
public static class MyThread extends Thread {
public static final ThreadLocal<MyObject> MY_OBJECT = new ThreadLocal<ThreadLocalTest.MyObject>() {
@Override
protected synchronized MyObject initialValue() {
return new MyObject(counter++);
}
};
@Override
public void run() {
for (int i = 0; i < 10; i++) {
MyObject myObj = MY_OBJECT.get();
myObj.work();
try {
Thread.sleep(100+RAND.nextInt(200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Runnable me = new ThreadLocalTest();
me.run();
}
@Override
public void run() {
final int n = 10;
for (int i = 1; i <= n; i++) {
MyThread mt = new MyThread();
mt.start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment