OnJava8-Examples/threads/ThreadLocalVariableHolder.java

72 lines
1.7 KiB
Java
Raw Normal View History

2016-07-05 14:46:09 -06:00
// threads/ThreadLocalVariableHolder.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Automatically giving each thread its own storage
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
import java.util.*;
class Accessor implements Runnable {
private final int id;
public Accessor(int idn) { id = idn; }
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()) {
ThreadLocalVariableHolder.increment();
System.out.println(this);
Thread.yield();
}
}
@Override
public String toString() {
return "#" + id + ": " +
ThreadLocalVariableHolder.get();
}
}
public class ThreadLocalVariableHolder {
private static ThreadLocal<Integer> value =
new ThreadLocal<Integer>() {
2016-01-25 18:05:55 -08:00
private SplittableRandom rand = new SplittableRandom(47);
2015-06-15 17:47:35 -07:00
@Override
protected synchronized Integer initialValue() {
return rand.nextInt(10000);
}
};
public static void increment() {
value.set(value.get() + 1);
}
public static int get() { return value.get(); }
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
ExecutorService es = Executors.newCachedThreadPool();
2015-06-15 17:47:35 -07:00
for(int i = 0; i < 5; i++)
2016-01-25 18:05:55 -08:00
es.execute(new Accessor(i));
2015-06-15 17:47:35 -07:00
TimeUnit.SECONDS.sleep(3); // Run for a while
2016-01-25 18:05:55 -08:00
es.shutdownNow(); // All Accessors will quit
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output: (First and last 10 Lines)
2015-06-15 17:47:35 -07:00
#2: 9259
#1: 962
#3: 1862
#4: 6694
#0: 556
#4: 6695
#4: 6696
#3: 1863
#1: 963
#2: 9260
________...________...________...________...________
#3: 3791
#2: 11096
#4: 8402
#4: 8403
#2: 11097
#3: 3792
#0: 2637
#1: 3032
#4: 8404
#2: 11098
2015-09-07 11:44:36 -06:00
*/