package concurrentLinkedQueueTest;
public class User {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package concurrentLinkedQueueTest;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ConcurrentLinkedQueueTest {
private static Queue<User> queue;
// 基于链接节点的***线程安全队列
static {
if (null == queue) {
queue = new ConcurrentLinkedQueue<User>();
}
}
/**
* 初始化创建队列
*/
public static void init() {
if (null == queue) {
queue = new ConcurrentLinkedQueue<User>();
}
}
/**
* 判断此队列是否有元素 ,没有返回true
*
* @return
*/
public static boolean isEmpty() {
return (queue.isEmpty());
}
/**
* 添加到队列方法,将指定元素插入此队列的尾部。
*
* @param u User对象
* @return 成功返回true,否则抛出 IllegalStateException
*/
public static boolean add(User u) {
return (queue.add(u));
}
/**
* 获取并移除此队列的头 ,如果此队列为空,则返回 null
*
* @return
*/
public static User getPoll() {
return (queue.poll());
}
/**
* 获取但不移除此队列的头;如果此队列为空,则返回 null
*
* @return
*/
public static User getPeek() {
return (queue.peek());
}
/**
* 获取size,速度比较慢
*
* @return
*/
public static int getQueueSize() {
return (queue.size());
}
public static void main(String[] args) {
// 先判断队列是否有数据
System.out.println(\”队列是否为空:\” + !isEmpty());
// 添加数据
User u1 = new User();
u1.setPassword(\”3333\”);
u1.setUserName(\”zhangsan\”);
queue.add(u1);
// 再次判断队列是否有数据
System.out.println(\”队列是否为空:\” + !isEmpty());
// 查看队列有多少条数据
System.out.println(\”队列数据条数:\” + getQueueSize());
User u2 = new User();
u2.setPassword(\”4444\”);
u2.setUserName(\”lisi\”);
queue.add(u2);
User u4 = new User();
u4.setPassword(\”5555\”);
u4.setUserName(\”王五\”);
queue.add(u4);
User u3 = getPeek();
System.out.println(\”userName=\” + u3.getUserName() + \”,password=\” + u3.getPassword());
// 把未删除的数据打印出来
for (int i = 0; i < 3; i++) {
User u5 = getPoll();
if (u5 != null) {
System.out.println(\”\\n获取队列数据并删除:\” + u5.getUserName() + \”—\” + u5.getPassword());
}
}
// 再次查看队列有多少条数据
System.out.println(\”队列数据条数:\” + getQueueSize());
}
}