優先度ブロッキング キューを作成しました。挿入は優先度に基づいて適切に行われます。キューの先頭を削除すると、キューの最後の要素がキューの先頭になり、手順が繰り返されます。123456789 をキューに挿入したとします。
First deleted : 1; queue elements :92345678
Second deleted: 9; queue elements :8234567
等々。
維持されていないキュー プロパティを達成する必要があります。
つまり、最初の削除: 1 つのキュー要素:23456789
2 番目の削除:2 つのキュー要素:3456789
package com.block.ui;
import java.util.Iterator;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class PriorityBlockQueSamplActivity extends Activity {
/** Called when the activity is first created. */
EditText et;
EditText et2;
Button b1;
Button b2;
Controller c ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
b1 =(Button)findViewById(R.id.button1);
b2 =(Button)findViewById(R.id.button2);
c= new Controller();
Message m = new Message();
m.mPriority=1;
m.Subject="1";
c.insert(m);
Message n = new Message();
n.mPriority=1;
n.Subject="2";
c.insert(n);
Message p = new Message();
p.mPriority=1;
p.Subject="3";
c.insert(p);
Message q = new Message();
q.mPriority=1;
q.Subject="4";
c.insert(q);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Iterator<Message> iter = c.getQueue().iterator();
while(iter.hasNext()){
Message m =iter.next();
Log.i("MESSAGE", "Element "+m.Subject+" priority :"+m.mPriority);
}
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Message m=c.getMessage();
c.delete(m);
}
});
}
}
そしてもう1クラス
`public class Controller {
private int queueSize=300;
Comparator<Message> comparator = new PriorityComaparator();
PriorityBlockingQueue<Message> qu = new PriorityBlockingQueue<Message>(queueSize,comparator);
public Controller() {
}
public void insert(Message msg) {
boolean status = qu.add(msg);
if (status)
log("Added successfully " + msg.Subject + " priority "
+ msg.mPriority + " size :" + qu.size());
else
log("Failed to add " + msg.Subject + " with priority "
+ msg.mPriority);
}
public void delete(Message msg) {
if (qu.contains(msg)) {
boolean status = qu.remove(msg);
if (status)
log("deleted successfully " + msg.Subject + " priority " + msg.mPriority
+ " size :" + qu.size());
else
log("Failed to delete " + msg.Subject + " with priority "+ msg.mPriority);
}
}
public Message getMessage() {
return qu.peek();
}
public PriorityBlockingQueue<Message> getQueue(){
return qu;
}
void log(String msg) {
Log.i("QUEUE", msg);
}
class PriorityComaparator implements Comparator<Message> {
@Override
public int compare(Message m, Message n) {
int y = ((Message) m).mPriority; // 1 -highest 3-least
int z = ((Message) n).mPriority;
if (y < z) {
return -1;
}
if (y > z) {
return 1;
}
return 0;
}
}
}`