在项目上使用的时候,关于LinkedBlockingQueue的使用,有一些疑问,就想着测试一下。
1.用同一个String对象,赋不同的值再一一放进去队列中
try {
BlockingQueue queue = new LinkedBlockingQueue();
String content = "content A";
queue.put(content);
content = "content B";
queue.put(content);
content = "content C";
queue.put(content);
new Thread(new Runnable() {
@Override
public void run() {
try {
while(true) {
if (queue.size() <= 0) {
break;
}
String str = (String) queue.take();
System.out.println(str);
}
} catch (Exception e) {
Log4j2Utils.getinstance().error("", e);
}
}
}).start();
} catch (Exception e) {
Log4j2Utils.getinstance().error("", e);
}
测试结果:
content A
content B
content C
结论:
从队列中拿出来的是不同的值。
2.新建一个对象,里面只有一个String,然后再使用同一个对象,赋不同的值,再拿出来看看
static class ContentDetail {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public static void main(String[] args) {
try {
BlockingQueue queue = new LinkedBlockingQueue();
ContentDetail contentDetail = new ContentDetail();
contentDetail.setTitle("content title A");
queue.put(contentDetail);
contentDetail.setTitle("content title B");
queue.put(contentDetail);
contentDetail.setTitle("content title C");
queue.put(contentDetail);
new Thread(new Runnable() {
@Override
public void run() {
try {
while(true) {
if (queue.size() <= 0) {
break;
}
ContentDetail contentDetail = (ContentDetail) queue.take();
System.out.println(contentDetail.getTitle());
}
} catch (Exception e) {
Log4j2Utils.getinstance().error("", e);
}
}
}).start();
} catch (Exception e) {
Log4j2Utils.getinstance().error("", e);
}
}
测试结果:
content title C
content title C
content title C
结论:
要是同一对象的话,以最后一次put进来的值为准