public class TestBlockingQueue { static long randomTime() { return (long) (Math.random() * 1000); }
public static void main(String[] args) { // 创建一个容量为100的阻塞队列 final BlockingQueue queue = new LinkedBlockingQueue<>(100); // 创建线程池 final ExecutorService exec = Executors.newFixedThreadPool(5); // 指定根目录 final File root = new File("F:\\JavaLib"); // 定义哨兵文件 final File exitFile = new File(""); // 记录读取和写入的文件数量 final AtomicInteger rc = new AtomicInteger(); final AtomicInteger wc = new AtomicInteger();
// 定义读线程任务 Runnable readTask = new Runnable() { public void run() { scanFile(root); scanFile(exitFile); // 添加哨兵 }
private void scanFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory() || pathname.getPath().endsWith(".java"); } }); for (File one : files) scanFile(one); } else { try { int index = rc.incrementAndGet(); System.out.println("Read: " + index + " " + file.getPath()); queue.put(file); } catch (InterruptedException e) {} } } };
exec.submit(readTask);
// 定义写线程任务 for (int i = 0; i <4; i++) { final int NO = i; Runnable writeTask = new Runnable() { String threadName = "Write" + NO;
public void run() { while (true) { try { Thread.sleep(randomTime()); int index = wc.incrementAndGet(); File file = queue.take(); if (file == exitFile) { queue.put(exitFile); // 再次添加哨兵 break; } System.out.println(threadName + ": " + index + " " + file.getPath()); } catch (InterruptedException e) {} } } }; exec.submit(writeTask); }
Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ...
[详细]
Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ...
[详细]