java阻塞队列使用实例
来源:互联网 发布:图片合成视频软件 编辑:程序博客网 时间:2024/06/03 16:45
package threadpool;import java.util.concurrent.BlockingQueue;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingDeque;import java.util.concurrent.atomic.AtomicInteger;/** * Created by jl on 2016/10/17. * 测试阻塞队列的使用(模拟有200个文件需要处理,由一个读线程去将文件加载到容量为100的阻塞队列,由四个写线程去进行文件处理) */public class TestBlockingQueue { // 能容纳100个文件 static final BlockingQueue<String> queue = new LinkedBlockingDeque<>(100); //读个数 static final AtomicInteger rc = new AtomicInteger(); //写个数 static final AtomicInteger wc = new AtomicInteger(); static long randomTime() { return (long) (Math.random() * 1000); } private static void scanFile(String name) { try { for (int i = 0; i < 200; i++) { queue.put("file" + i); } queue.put("");//放置结束标置 } catch (InterruptedException e) { e.printStackTrace(); } } private static void writeFile() { while (true) { try { Thread.sleep(randomTime()); int index = wc.incrementAndGet(); String name = queue.take(); System.out.println(Thread.currentThread() + "=》" + name + "写操作完成,已完成:" + index); //队列已经无对象 if ("".equals(name)) { // 再次添加”标志”,以让其他线程正常退出 queue.put(""); break; } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { //线程池 final ExecutorService exec = Executors.newFixedThreadPool(5); Runnable read = new Runnable() { @Override public void run() { scanFile("noNeed"); } }; Runnable write = new Runnable() { @Override public void run() { writeFile(); } }; //从线程池起一个读线程 exec.submit(read); //从线程池起四个写线程 for (int i = 0; i < 4; i++) { exec.submit(write); } exec.shutdown(); }}
0 0
- java阻塞队列使用实例
- java阻塞队列BlockingQueue使用实例
- Java阻塞队列使用
- Java中的阻塞队列ArrayBlockingQueue的使用
- Java 使用线程经验之阻塞队列
- java 使用ReentrantLock Condition实现阻塞队列
- 【java并发】阻塞队列的使用
- Java阻塞队列BlockingQueue的使用
- Java中阻塞队列的使用
- Java多线程____BlockingQueue阻塞队列使用
- 使用java来实现阻塞队列
- Java阻塞队列使用小例
- 基于Java阻塞队列实例(文件及文件内容搜索)
- 【多线程】 java线程实例(测试阻塞队列&&线程池)
- java阻塞队列以及非阻塞队列
- java阻塞队列与非阻塞队列
- 阻塞队列使用---ArrayBlockingQueue
- 阻塞队列BlockingQueue使用
- UVA - 10422 Knights in FEN
- 赵雄飞uc讲解20110216
- 有关TimesTen的一些博文
- JVM 参数设置
- YARN的内存和CPU配置
- java阻塞队列使用实例
- 打印菱形
- java基础1
- Django QuerySet的基本API
- MFC TeeChart 用法整理二
- Butterknife7.0.1混淆后报空指针问题
- 写论文的word技巧
- Detailed Item Cost Report (XML) timed out waiting for the Output Post-processor to finish
- 利用mybatis插件反向生成javabean