I run requestor thread
Task t = new Task(s1, s2, c, p);
Requestor req = new Requestor(queue, t);
req.start();
It add task to queue and run service thread
queue.add(task); // my class
Service ser = new Service(queue);
ser.start();
add method
public void add(Task t) {
synchronized (mutex) {
queue.add(t); // PriorityQueue<Task>
list.clear(); // DefaultListModel
for (Task ta : queue)
list.addElement(ta);
}
}
Service’s run method
task = queue.pop(); // my class
...
queue.add(task);
pop method
public Task pop() {
synchronized (mutex) {
ArrayList<Task> al = new ArrayList<Task>();
Task tmp = queue.remove();
al.add(tmp);
while (tmp.isFinish() && !queue.isEmpty()) {
tmp = queue.remove();
al.add(tmp);
}
al.remove(al.size()-1);
for (Task t : al) {
queue.add(t);
}
list.clear();
for (Task ta : queue)
list.addElement(ta);
return tmp;
}
}
queue var is
Comparator<Task> cmp = new TaskComparator();
queue = new PriorityQueue<Task>(20, cmp);
comparator
public class TaskComparator implements Comparator<Task> {
@Override
public int compare(Task o1, Task o2) {
return o1.getPriority() - o2.getPriority();
}
}
generally this priority queue sort randomly, some time i can see
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 >= 0
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.DefaultListModel.getElementAt(DefaultListModel.java:70)
...
—-edit
GUI
private Queue queue;
...
_add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
...
Task t = new Task(s1, s2, c, p);
Requestor req = new Requestor(queue, t);
req.start();
}
});
...
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
DefaultListModel model = new DefaultListModel();
JList _list = new JList(model);
scrollPane.setViewportView(_list);
queue = new Queue(model);
— edit
I implements comparable to task class. If i return 1 it always add new o elements on bottom, when I return -1 it always add new element on top, but when
@Override
public int compareTo(Task o) {
if (pr == o.getPriority())
return 0;
else if (pr > o.getPriority())
return 1;
else
return -1;
}
It sort as it want
PriorityQueue is a heap, and it’s rebuilding when you use remove() method.