【问题标题】:Get custom Thread's property through Runnable task通过 Runnable 任务获取自定义 Thread 的属性
【发布时间】:2016-06-23 02:01:16
【问题描述】:

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

【问题讨论】:

    标签: java multithreading threadpool


    【解决方案1】:

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

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

    【讨论】:

    • 我完全忘记了类型转换,这应该可以。感谢您的快速响应,遗憾的是我无法投票:)
    猜你喜欢
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多