我有自定义线程类,它有一个属性。所述属性从自定义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<< ? */
{
{
答案 0 :(得分:2)
您可以通过调用run
来访问Thread.currentThread()
方法中的当前主题。然后你只需要把它投射到MyThread
。
class MyRunnable implements Runnable {
public void run(){
MyThread myThread = (MyThread) Thread.currentThread();
System.out.println(myThread.getProperty());
}
}