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;
}
java
}安全
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());
}
}
app