通过 Runnable 任务获取自定义 Thread 的 属性

Get custom Thread's property through Runnable task

我有自定义线程 class,其中有一个 属性。表示 属性 从自定义 ThreadFactory 传递过来。我能以某种方式从 Runnable 任务中获取线程对象的 属性 吗?

展示想法的示例代码(可能有错误):

public static void main(String[] args){
    MyFactory factory = new MyFactory("abc");
    ExecutorService e = Executors.newFixedThreadPool(4,factory);
    MyRunnable r = new MyRunnable();
    e.submit(r);
}

public class MyFactory implements ThreadFactory{
    private String property;
    public MyFactory(String p){
        property = p;
    }
    public MyThread newThread(Runnable r){
        MyThread out = new MyThread(r, property);
    }
}

public class MyThread extends Thread{
    private String property;
    public MyThread(Runnable r, String p){
        super(r);
        property = p;
    }
    public String getProperty(){
        return property;
    }
}

public class MyRunnable implements Runnable{
    public void run(){
        /* Can I get my "abc" property from >>HERE<< ? */
    {
{

您可以通过调用 Thread.currentThread()run 方法中访问当前线程。然后你只需要将它转换为 MyThread.

class MyRunnable implements Runnable {
    public void run(){
        MyThread myThread = (MyThread) Thread.currentThread();
        System.out.println(myThread.getProperty());
    }
}