本文主要根据《Java程序员修炼之道》整理的代码笔记片段
TransferQueue对象 如果接收线程处于等待状态,transfer()马上把工作项传给它,否则就会阻塞直到取走工作项 [高效]
即正在处理的工作项的线程在交付当前工作之前(被取走之前),不开始其他工作项的处理。
public abstract class MicroBlogThread extends Thread {
protected final TransferQueue<Update> updates;
protected String text = "";
protected final int pauseTime;
private boolean shutdown = false;
public MicroBlogThread(TransferQueue<Update> lbq_, int pause_) {
updates = lbq_;
pauseTime = pause_;
}
public synchronized void shutdown() {
shutdown = true;
}
@Override
public void run() {
while (!shutdown) {
doAction();
try {
Thread.sleep(pauseTime);
} catch (InterruptedException e) {
shutdown = true;
}
}
}
public abstract void doAction();
}
public class MicroBlogThreadMain {
public static void main(String[] a) {
final Update.Builder ub = new Update.Builder();
final TransferQueue<Update> lbq = new LinkedTransferQueue<>();
//如果接收线程处于等待状态,transfer()马上把工作项传给它,否则就会阻塞直到取走工作项 [高效]
MicroBlogThread t1 = new MicroBlogThread(lbq, 10) {
public void doAction() {
text = text + "X";
Update u = ub.author(new Author("Tallulah")).updateText(text).build();
boolean handed = false;
try {
handed = updates.offer(u, 100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
if (!handed)
System.out
.println("Unable to handoff Update to Queue due to timeout");
}
};
MicroBlogThread t2 = new MicroBlogThread(lbq, 1000) {
public void doAction() {
@SuppressWarnings("unused")
Update u = null;
try {
u = updates.take();
} catch (InterruptedException e) {
return;
}
}
};
t1.start();
t2.start();
}
}
如果采用LinkedBlockingQueue 必须设置大小,不然相连线程池塞入过快,会内存溢出