欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jdk1.5后增加的线程安全的队列ConcurrentLinkedQueue的用法 JavaJ#thread 

程序员文章站 2022-03-28 23:23:39
...
1.最简单的Helloworld.
需要注意的是这个size()也是不同步的,和list一样,要得到需要遍历一次。
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;


public class testConcurrentLinkedQueue {
   public static void main(String[] args) {
   Queue<String> queue=new ConcurrentLinkedQueue<String>();
   queue.add("aa");
   queue.add("bb");
   queue.add("cc");
   queue.add("dd");
   queue.add("ee");
   System.out.println(queue.poll());
   System.out.println(queue.poll());
   System.out.println(queue.poll());
   System.out.println(queue.poll());
   System.out.println(queue.poll());
   System.out.println(queue.poll());   
}
}
2.含有优先级的,缺点优先级越多,分支越多。
import java.util.PriorityQueue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class PriorityQueueTest {

    public static void main(String[] args) {
        ConcurrentLinkedQueue<String> highPriority = new ConcurrentLinkedQueue<String>(); //高优先级
        ConcurrentLinkedQueue<String> lowPriority = new ConcurrentLinkedQueue<String>();  //低优先级
        
        highPriority.add("aaa");
        highPriority.add("bbb");
        highPriority.add("111");
        
        lowPriority.add("ccc");
        lowPriority.add("ddd");
        lowPriority.add("222");
        
        int i = 0 ,j = 0, k=0;
        while(true){
            while(true){
                if(!highPriority.isEmpty()){
                    System.out.print(highPriority.remove());
                    i++;
                    k++;
                    System.out.println(", i = "+i+", k="+k);
                    break;
                }
                if(!lowPriority.isEmpty()){
                    System.out.print(lowPriority.remove());
                    j++;
                    k++;
                    System.out.println(", j = "+j+", k="+k);
                    break;
                }
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
相关标签: Java J# thread