gpt4 book ai didi

java - ThreadLocal 与 Runnable 中的局部变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:12 25 4
gpt4 key购买 nike

ThreadLocalRunnable 中的局部变量哪个优先?出于性能原因。我希望使用局部变量能为 cpu 缓存等提供更多机会。

最佳答案

Which one among ThreadLocal or a local variable in Runnable will be preferred.

如果您有一个在线程类(或 Runnable)中声明的变量,那么局部变量将起作用,您不需要 ThreadLocal

new Thread(new Runnable() {
// no need to make this a thread local because each thread already
// has their own copy of it
private SimpleDateFormat format = new SimpleDateFormat(...);
public void run() {
...
// this is allocated per thread so no thread-local
format.parse(...);
...
}
}).start();

另一方面,当您执行公共(public)代码时,ThreadLocal 用于在每个线程的基础上保存状态。例如,SimpleDateFormat(不幸的是)不是线程安全的,所以如果你想在多线程执行的代码中使用它,你需要将一个存储在 ThreadLocal 中,所以每个线程都有自己的格式版本。

private final ThreadLocal<SimpleDateFormat> localFormat =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(...);
}
};
...
// if a number of threads run this common code
SimpleDateFormat format = localFormat.get();
// now we are using the per-thread format (but we should be using Joda Time :-)
format.parse(...);

Web 请求处理程序是必要时的一个示例。线程在我们控制之外的某种池中分配到 Jetty land(例如)中。出现一个与您的路径匹配的 Web 请求,因此 Jetty 调用您的处理程序。您需要有一个 SimpleDateFormat 对象,但由于其限制,您必须为每个线程创建一个。这就是您需要 ThreadLocal 的时候。当您正在编写可由多个线程调用的可重入代码并且您希望为每个线程存储一些内容时。

相反,如果您想将参数传递给 Runnable,那么您应该创建自己的类,然后您可以访问构造函数并传递参数。

new Thread(new MyRunnable("some important string")).start();
...
private static class MyRunnable implements {
private final String someImportantString;
public MyRunnable(String someImportantString) {
this.someImportantString = someImportantString;
}
// run by the thread
public void run() {
// use the someImportantString string here
...
}
}

关于java - ThreadLocal 与 Runnable 中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10115537/

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