1、类介绍
可以用原子方式更新的 int 值。
2、使用场景
主要用于在高并发环境下的高效程序处理。使用非阻塞算法来实现并发控制。
3、相关实例
在并发情况下使用AtomicInteger实现原子化更新进行读写文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| public class AtomicTest {
static long randomTime() { return (long) (Math.random() * 1000); } public static void main(String[] args) { final BlockingQueue<File> queue = new LinkedBlockingQueue<File>(100); final ExecutorService exec = Executors.newFixedThreadPool(5); final File root = new File("D:\\\ISO"); final File exitFile = new File(""); final AtomicInteger rc = new AtomicInteger(); final AtomicInteger wc = new AtomicInteger(); Runnable read = new Runnable() { public void run() { scanFile(root); scanFile(exitFile); } public void scanFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory() || pathname.getPath().endsWith(".iso"); } }); for (File one : files) scanFile(one); } else { try { int index = rc.incrementAndGet(); System.out.println("Read0: " \+ index + " " \+ file.getPath()); queue.put(file); } catch (InterruptedException e) { } } } }; exec.submit(read); for (int index = 0; index < 4; index++) { final int num = index; Runnable write = new Runnable() { String threadName = "Write" \+ num; 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(write); } exec.shutdown(); }
}
|