您可以使用LinkedBlockingDeque。一个例子:
public class ProducerConsumer {
public static void main(String[] args) {
final LinkedBlockingDeque<Message> queue = new LinkedBlockingDeque<>(10);
final AtomicLong id = new AtomicLong(0);
final Timer producer = new Timer(true);
producer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
queue.add(new Message( String.format("msg: %s" , id.incrementAndGet() ) ) );
}
}, 10, 10);
// consume
for(;;) {
try {
Message msg = queue.take();
System.out.println( msg );
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private static class Message {
private final String id;
public Message(String id) {
this.id = id;
}
public String getId() {
return id;
}
@Override
public String toString() {
return String.format("Message [id=%s]", id);
}
}
}