막지 않고 일으킨 대화
1792 단어 막히다
private ConcurrentLinkedQueue<PostMassage> postMassages = new ConcurrentLinkedQueue<PostMassage>();
...
public void run() {
while (true) {
PostMassage post =postMassages.peek();
if(post!=null){
...
postMassages.poll();
}
...
}
}
이 코드를 보면while 순환이 끊임없이 진행되는데, 대기열이 비어 있는 상황에서도 마찬가지다.이것의while 조작은 매우 늦다 cpu.해결 방법은 차단의 형식으로 다음과 같다.
...
sliceQueue = new LinkedBlockingQueue<byte[]>();
...
public void run() {
while(true) {
try {
data = sliceQueue.take();
...
} catch(Exception e) {
...
}
}
}
이것은 막혔고 이상한 처리를 해서 이것을 더욱 건장하게 했다.take가 막히는 원리를 보아라. 신호량을 채택한 것이다. 이것은wait notify와 매우 유사하다
public E take() throws InterruptedException {
E x;
int c = -1;
final AtomicInteger count = this.count;
final ReentrantLock takeLock = this.takeLock;
takeLock.lockInterruptibly();
try {
while (count.get() == 0) {
notEmpty.await();
}
x = dequeue();
c = count.getAndDecrement();
if (c > 1)
notEmpty.signal();
} finally {
takeLock.unlock();
}
if (c == capacity)
signalNotFull();
return x;
}