JAVA在线程中获取runnable对象

时间:2012-09-29 10:43:43

标签: java multithreading

我正在使用这个标准构造函数:

   new Thread(myRunnable);

其中myRunnable是具有Runnable接口的自定义对象。

在线程进程中我需要访问该runnable对象(告诉进程状态和进度),我该怎么办?

如果我的对象是我将使用的线程:

   (MyThread) Thread.getCurrentThread()

但是当runnable作为参数传递时我无法得到它。

修改

这是我的代码结构:

public abstract class ProgressThread{
    private float progress;     //... progress getter, setter...    
}

public class MyRunnable extends ProgressThread implements Runnable{
    public void run(){
        //starting processes...
        Job1 j1=new Job1().do();
        Job1 j2=new Job2().do();
    }

    private class Job1(){
        for(int i=0;i<10;i++){
            // do something
            float progress=i/10;
            // set job progress in thread
            Thread.getCurrentThread().getRUNNABLE().setProgress(progress);
        }
    }

}

这就是我需要getRUNNABLE()方法(或解决方法!)的原因。 感谢。

1 个答案:

答案 0 :(得分:6)

只需保留对runnable的引用,以便在需要时可以访问它

Runnable myRunnable = ...
new Thread(myRunnable).start();

// do what you wish with the runnable
myRunnable.foo();
相关问题