gpt4 book ai didi

java - Bruce Eckel 《Java 思维》第 4 版,ThreadLocal 变量持有者

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:52 27 4
gpt4 key购买 nike

书中的两个片段(并发章节):

 class Accessor implements Runnable {
private final int id;

public Accessor(int idn) {
id = idn;
}

public void run() {
while(!Thread.currentThread().isInterrupted()) {
ThreadLocalVariableHolder.increment();
System.out.println(this);
Thread.yield();
}
}

public String toString() {
return "#" + id + ": " +
ThreadLocalVariableHolder.get();
}
}

public class ThreadLocalVariableHolder {

private static ThreadLocal<Integer> value =
new ThreadLocal<Integer>(); /*{
private Random rand = new Random(47);
protected synchronized Integer initialValue() {
return rand.nextInt(10000);
}
};*/

public static void increment() {
value.set(value.get() + 1);
}

public static int get() {
return value.get();
}

public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();

for(int i = 0; i < 5; i++)
exec.execute(new Accessor(i));

TimeUnit.SECONDS.sleep(3); // Run for a while
exec.shutdownNow();
// All Accessors will quit
}
}

ThreadLocalVariableHolder类中是内部类ThreadLocal,其方法initialValue和属性rand未显式使用。如果我评论类(class)的全部内容(就像我在这里所做的那样),它仍然会产生类似的结果。我想,这段代码已经过时了。你知道为什么这段代码在内部类中,其目的是什么吗?

最佳答案

我怀疑,如果我运行你的代码,它会在 increment() -> value.get() 处抛出 NPE

这是有效的,因为 ThreadLocal 中的默认实现将返回 null

protected T initialValue() {
return null;
}

来自JavaDoc

Returns the current thread's "initial value" for this thread-local variable. This method will be invoked the first time a thread accesses the variable with the get method, unless the thread previously invoked the set method, in which case the initialValue method will not be invoked for the thread. Normally, this method is invoked at most once per thread, but it may be invoked again in case of subsequent invocations of remove followed by get.

This implementation simply returns null; if the programmer desires thread-local variables to have an initial value other than null, ThreadLocal must be subclassed, and this method overridden. Typically, an anonymous inner class will be used.

关于java - Bruce Eckel 《Java 思维》第 4 版,ThreadLocal 变量持有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25400934/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com