我必须创建一个模拟并发线程的应用程序。“服务器”创建了许多“线程”,并将它们存储在队列中。每个“线程”都定义了完成执行的时间。服务器从队列中轮询每个“线程”以完成10 ms的任务。如果线程完成了他的工作,它将从队列中移除。如果没有,则在队列末尾添加。我使用这个应用程序PriorityQueue。问题是,我编写的代码没有给出预期的输出;一个“线程”被执行,直到他的执行时间结束。我该如何解决这个问题?
SimulatedThread类
public class SimulatedThread {
private int executionTime;
private Integer id;
private int executedTime;
private boolean finished;
public SimulatedThread(){
executedTime = 0;
executionTime = 0;
setFinished(false);
}
//getters and setters
}服务器类
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;
public class Server {
final int TIME = 10;
final int TH_NO = 10;
//priority
final int MIN_P = 1;
final int MAX_P = 100;
//execution time
final int MIN_E = 10;
final int MAX_E = 100;
private PriorityQueue<SimulatedThread> activeThreads;
public Server() {
Comparator<SimulatedThread> comparator = new SimulatedThreadComparator();
activeThreads = new PriorityQueue<SimulatedThread>(10,comparator);
}
public void createThreads(){
for( int i = 0; i < TH_NO; i++){
SimulatedThread th = new SimulatedThread();
th.setExecutionTime(generator(MAX_E, MIN_E));
th.setId(generator(MAX_P,MIN_P));
System.out.println("New thread has been created");
System.out.println(th.toString());
activeThreads.add(th);
}
}
public void executeThreads(){
while(!activeThreads.isEmpty()){
SimulatedThread th = activeThreads.poll();
if(!th.isFinished()){
try {
Thread.sleep(TIME);
th.setExecutedTime(th.getExecutedTime() + TIME);
System.out.println(th.toString());
if((th.getExecutionTime() - th.getExecutedTime()) <= 0 ){
th.setFinished(true);
} else{
activeThreads.add(th);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
activeThreads.removeAll(activeThreads);
}
private int generator(int max, int min){
Random rand = new Random();
return rand.nextInt((max - min) + 1) - min;
}
public static void main(String[] args){
Server s = new Server();
s.createThreads();
s.executeThreads();
}编辑
SimulatedThreadComparator类
import java.util.Comparator;
public class SimulatedThreadComparator implements Comparator<SimulatedThread> {
@Override
public int compare(SimulatedThread o1, SimulatedThread o2) {
return o1.getId().compareTo(o2.getId());
}
}发布于 2014-06-01 15:53:58
这就解释了:由于优先级是ID,最后一个被激活的线程将返回到队列的头,并且是下一个激活的线程,直到它完成为止。
也许您应该比较执行的时间而不是ID?
https://stackoverflow.com/questions/23971181
复制相似问题