gpt4 book ai didi

java - 在另一个Runnable实现类中传递Runnable实例,其中前者的run()方法需要后者的引用

转载 作者:太空宇宙 更新时间:2023-11-04 10:29:30 25 4
gpt4 key购买 nike

我有一个类“ResourceConsumerThread”,它扩展了 Thread 并定义了一些行为。此类的多个实例(即多个线程)将具有不同的行为。我试图在创建 ResourceConsumerThread 类的实例时通过功能接口(interface)(Runnable)传递这些行为。 ResourceConsumerThread 的 run() 方法只是调用 lambda 的方法 - run()。但是,我的要求是我传递的 lambda 需要引用它所传递到的 ResourceConsumerThread 对象。

 public class ResourceConsumingThread extends Thread {
//threads which have acquired resources that this thread is asking for.
private List<ResourceConsumingThread> dependencyList;
private List<Resource> acquiredResources;
private List<Resource> requestedResources;
private volatile boolean isDeadlockDetected;
private final String id;
private static int threadIdGenerator;
private final Runnable runnableBody;

private ResourceConsumingThread( Runnable runnableBody) {
this.dependencyList = new ArrayList<>();
this.acquiredResources = new ArrayList<>();
this.requestedResources = new ArrayList<>();
this.id = "T" + threadIdGenerator++;
this.runnableBody = runnableBody;
}

@Override
public void run() {
System.out.println("Running body for thread : " + id);
if(runnableBody != null){
runnableBody.run();
}else{
System.out.println("ERROR...threadBody can't be null.");
}
}
}

此类的用户将像下面这样使用它:

public void callerMethod(){
ResourceConsumingThread t1 = lockManager.createNewThread(new Runnable() {
@Override
public void run() {
lockManager.acquireLockOnResourceForThread(new Resource(), t1);
}
});
}

但是,由于 t1 尚未构建,我无法在 run() 方法中使用它 - 我收到编译器错误。

知道如何实现这一点,即使它涉及一些设计返工?主要要求是:

  1. LockManager.acquireLockOnResourceForThread() 需要知道哪个 ResourceConsumingThread 实例正在请求哪个资源。
  2. ResourceConsumingThread 的 run() 方法应该能够在单独的线程中执行不同的逻辑。

更新了我正在尝试的答案(不确定这样做是否正确)。仍在等待社区提供更多潜在解决方案。

final Map<String, Resource> resourceMap = new HashMap<>();
resourceMap.put("R1", new Resource());

final ResourceConsumingThread t1 = new ResourceConsumingThread();
Runnable t1Runnable = new Runnable() {
@Override
public void run() {
lockManager.acquireLockOnResourceForThread(resourceMap.get("R1"), t1);
}
};
t1.setRunnableBody(t1Runnable);
t1.start();
t1.join();

更新(在 @Cliff 发表评论之后):

 ResourceConsumingThread t = lockManager.createNewThread(() -> {

lockManager.acquireLockOnResourceForThread(new Resource(), (ResourceConsumingThread) Thread.currentThread());
});

最佳答案

您可以简单地在匿名内部类中使用this:

public void callerMethod(){
ResourceConsumingThread t1 = lockManager.createNewThread(new Runnable() {
@Override
public void run() {
lockManager.acquireLockOnResourceForThread(new Resource(), this);
}
});
}

这将传递对 Runnable 的引用,该引用在 callerMethod 中称为 t1

关于java - 在另一个Runnable实现类中传递Runnable实例,其中前者的run()方法需要后者的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50176501/

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