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

时间:2016-06-22 17:51:47

标签: java multithreading threadpool

我有自定义线程类,它有一个属性。所述属性从自定义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<< ? */
    {
{

1 个答案:

答案 0 :(得分:2)

您可以通过调用run来访问Thread.currentThread()方法中的当前主题。然后你只需要把它投射到MyThread

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