gpt4 book ai didi

java - 线程 : Retrieving then executing object from ArrayList

转载 作者:行者123 更新时间:2023-11-30 04:36:57 25 4
gpt4 key购买 nike

我正在使用线程,需要首先从集合中检索对象,然后执行该对象中的方法。我使用 ArrayList.get(0) 检索第一个元素,但现在如何为刚刚检索的 Runnable 对象执行 run() 方法?

这是迄今为止我的代码:

public class MyThread extends Thread{

//Instance Variables
private List<Runnable> requestQueue;

//Constructor
public MyThread() {
requestQueue = new LinkedList<Runnable>();
}

//Methods
public void run() {
while (!requestQueue.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
requestQueue.get(0);
}
}

}

最佳答案

当您的队列为空时,您可以运行:

new Thread(requestQueue.get(0)).start();

顺便说一句:您应该会遇到循环名称冲突,表明您无法扩展Thread。您可以将该类重命名为 MyThread

另请查看ExecutorService作为抽象与原始线程等较低级别抽象相关的许多复杂性的一种手段。

关于java - 线程 : Retrieving then executing object from ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261869/

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