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

最佳答案


如果您在线程的类(或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,则需要在SimpleDateFormat中存储一个,以便每个线程都能获得自己的格式版本。
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区域中分配的(例如)在我们无法控制的某种池中。出现一个与您的路径匹配的Web请求,因此Jetty调用您的处理程序。您需要有一个ThreadLocal对象,但是由于其限制,您必须为每个线程创建一个。那就是您需要Runnable的时候。当您编写可被多个线程调用的可重入代码时,您想为每个线程存储一些内容。
相反,如果要将参数传递给ojit_code,则应创建自己的类,然后可以访问构造函数并传递参数。
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
       ...
    }
}

10-07 19:09
查看更多