本文主要是介绍用队列ConcurrentLinkedQueue模拟生产者和消费者,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
用队列ConcurrentLinkedQueue模拟生产者和消费者
package com.queue;import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;/*** Created by lifeng* 2017/12/20 10:15*/
public class QueueTest2 {public static void main(String[] args) {Queue<String> queue = new ConcurrentLinkedQueue<String>();Thread t1 = new Thread(new Producter(queue));Thread t3 = new Thread(new Producter(queue));Thread t2 = new Thread(new Consumer(queue));Thread t4 = new Thread(new Consumer(queue));t1.start();t2.start();t3.start();t4.start();}
}class Producter implements Runnable{private Queue<String> queue;public Producter(Queue<String> queue){this.queue = queue;}@Overridepublic void run() {while (true){synchronized(Integer.class){if(queue.size() < 5000){String data = UUID.randomUUID().toString();boolean flag = queue.offer(data);System.out.println("线程"+Thread.currentThread().getName()+"生产:"+ (flag==true ? data:""));}else{try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}}}
}class Consumer implements Runnable{private Queue<String> queue;public Consumer(Queue<String> queue){this.queue = queue;}@Overridepublic void run() {while (true){synchronized(String.class){if(!queue.isEmpty()){String data = queue.poll();System.out.println("线程"+Thread.currentThread().getName()+"消费:"+ data);}else{try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}}}
}
这篇关于用队列ConcurrentLinkedQueue模拟生产者和消费者的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!