我有一个具有属性的自定义线程类。所述属性从自定义 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());
}
}
关于java - 通过Runnable任务获取自定义Thread的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37975062/