gpt4 book ai didi

java - 通过 Runnable 任务获取自定义线程的属性

转载 作者:行者123 更新时间:2023-11-30 08:35:55 25 4
gpt4 key购买 nike

我有一个自定义线程类,它有一个属性。所述属性从自定义 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 任务获取自定义线程的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37975062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com