我有一个使用阻塞的生产者/消费者的实现,我像这样启动它们
BlockingQueue<Object> myQueue1 = new LinkedBlockingQueue<Object>();
new Thread(new SmsInProducer(myQueue1, 100)).start();
for (int i = 0; i < 100; i++ ) {
new Thread(new SmsInConsumer(myQueue1)).start();
}
Producer 内部是这样的
public class SmsInProducer implements Runnable {
protected BlockingQueue queue;
protected int MAX_RECORDS = 5000;
@SuppressWarnings("rawtypes")
public SmsInProducer(BlockingQueue theQueue, int maxRecord) {
this.queue = theQueue;
this.MAX_RECORDS = maxRecord;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
int totalRecords = MAX_RECORDS - queue.size();
if (totalRecords > 0) {
List<Map> tList = Sql.updateTRECEIVE();
if (tList != null && !tList.isEmpty()) {
queue.addAll(tList);
}
}
// wait for 1 second
try { Thread.sleep(Parameter.replyWaitTime * 1000); } catch(Exception e) {}
}
}
消费者看起来像这样
public class SmsInConsumer implements Runnable {
@SuppressWarnings("rawtypes")
protected BlockingQueue queue;
@SuppressWarnings("rawtypes")
public SmsInConsumer(BlockingQueue theQueue) {
this.queue = theQueue;
}
@SuppressWarnings("rawtypes")
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Object obj = queue.take();
Map map = (Map) obj;
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (Exception e) {
e.printStackTrace();
} finally {
try { Thread.sleep(Parameter.replyWaitTime * 1000); } catch(Exception e){}
}
}
}
但是一段时间后它变得非常慢,无论如何我可以保持它非常快吗?