【发布时间】:2018-06-09 04:24:01
【问题描述】:
我目前正在尝试实现一个可以在几个不同线程中运行的系统列表:
1) 第一个线程正在监听传入的请求并将它们添加到列表中。
2) 为每个请求创建一个新线程来执行某些操作。
3) 另一个线程遍历列表,检查每个请求的状态,并在完成后将它们从列表中删除。
现在,我在一个非常简化的伪代码中拥有它的方式可以在下面查看:
private List<Job> runningJobs = new ArrayList<>(); // our list of requests
private Thread monitorThread;
private Runnable monitor = new Runnable() { // this runnable is later called in a new thread to monitor the list and remove completed requests
@Override
public void run() {
boolean monitorRun = true;
while(monitorRun) {
try {
Thread.sleep(1000);
if (runningJobs.size()>0){
Iterator<Job> i = runningJobs.iterator();
while (i.hasNext()) {
try {
Job job = i.next();
if (job.jobStatus() == 1) { // if job is complete
i.remove();
}
}
catch (java.util.ConcurrentModificationException e){
e.printStackTrace();
}
}
}
if (Thread.currentThread().isInterrupted()){
monitorRun = false;
}
} catch (InterruptedException e) {
monitorRun = false;
}
}
}
};
private void addRequest(Job job){
this.runningJobs.add(newJob);
// etc
}
简而言之,Runnable 监视器是在第三个线程中连续运行的;第一个线程偶尔会调用 addRequest()。
虽然我当前的实现有些工作,但我担心这里的操作顺序和可能的 java.util.ConcurrentModificationException(而且系统一点也不健壮)。我确信有更好的方法来组织这个混乱。
什么是正确或更好的方法?
【问题讨论】:
-
你为什么不使用
BlockQueue实现? -
坦率地说,我根本不知道它的存在。我去看看。
标签: java multithreading list