블러킹 우선순위 큐를 만들어야 하는 상황이 발생. 직접 구현해야 하나 고민 하다 java concurrent 부분을 뒤적이니 좋은 놈이 있더라.
PriorityBlockingQueue <- 임마를 기본으로 제공해주니.. 좋더란 말이쥐..
간단한 사용 샘플을 올린다.
PriorityBlockingJobQueue.java
- 별거 없이
PriorityBlockingQueue 임마를 싱글톤 패턴으로 래핑한 클래스
package queue;
import java.util.concurrent.PriorityBlockingQueue;
public class PriorityBlockingJobQueue {
final static PriorityBlockingJobQueue instance = new PriorityBlockingJobQueue();
PriorityBlockingQueue<PriorityJob> queue = new PriorityBlockingQueue<PriorityJob>(10, new CompareDescending());
public static PriorityBlockingJobQueue getInstance() {
return instance;
}
public void put(PriorityJob job){
queue.put(job);
}
public PriorityJob take() {
try {
return (PriorityJob) queue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
CompareDescending.java
- 내림차순으로 정렬 클래스
package queue;
import java.util.Comparator;
public class CompareDescending implements Comparator<PriorityJob>{
@Override
public int compare(PriorityJob o1, PriorityJob o2) {
return o2.getPriority().compareTo(o1.getPriority());
}
}
PriorityJob.java
- 우선순위 Job 클래스
package queue;
public class PriorityJob {
String priority; // 우선순위
Object job; // Job
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public Object getJob() {
return job;
}
public void setJob(Object job) {
this.job = job;
}
}
PriorityBlockingQueueTest.java
- 테스트 클래스
package queue;
public class PriorityBlockingQueueTest {
public void excute() {
PriorityJob job1 = new PriorityJob();
job1.setPriority("1");
job1.setJob("1");
PriorityBlockingJobQueue.getInstance().put(job1);
PriorityJob job2 = new PriorityJob();
job2.setPriority("0");
job2.setJob("0");
PriorityBlockingJobQueue.getInstance().put(job2);
PriorityJob job3 = new PriorityJob();
job3.setPriority("3");
job3.setJob("3");
PriorityBlockingJobQueue.getInstance().put(job3);
PriorityJob job4 = new PriorityJob();
job4.setPriority("1");
job4.setJob("1");
PriorityBlockingJobQueue.getInstance().put(job4);
PriorityJob job5 = new PriorityJob();
job5.setPriority("5");
job5.setJob("5");
PriorityBlockingJobQueue.getInstance().put(job5);
PriorityJob job6 = new PriorityJob();
job6.setPriority("0");
job6.setJob("0");
PriorityBlockingJobQueue.getInstance().put(job6);
while(true) {
System.out.println(PriorityBlockingJobQueue.getInstance().take().getJob());
}
}
public static void main(String[] args) {
new PriorityBlockingQueueTest().excute();
}
}
결과 출력
5
3
1
1
0
0
'java > concurrency' 카테고리의 다른 글
[Concurrency] - ExecutorService 의 awaitTermination() 사용하기 (0) | 2010.06.29 |
---|---|
[Concurrency] - java.util.concurrent.locks.Condition (0) | 2010.06.29 |
[Concurrency] - LOCK(락) - ReentrantReadWriteLock(2) (0) | 2010.06.29 |
[Concurrency] - LOCK(락) - ReentrantReadWriteLock(1) (0) | 2010.06.29 |
[Concurrency] - ExecutorService 의 invokeAll() 사용하기 (0) | 2010.06.29 |