在使用多线程的时候有时候我们会使用 java.util.concurrent.Executors的线程池,当多个线程异步执行的时候,我们往往不好判断是否线程池中所有的子线程都已经执行完毕,但有时候这种判断却很有用,例如我有个方法的功能是往一个文件异步地写入内容,我需要在所有的子线程写入完毕后在文件末尾写“---END---”及关闭文件流等,这个时候我就需要某个标志位可以告诉我是否线程池中所有的子线程都已经执行完毕,我使用这种方式来判断。
1 public classMySemaphore {2
3 public static void main(String[] args) throwsIOException, InterruptedException {4 final File stream = new File("c:\\temp\\stonefeng\\stream.txt");5 final OutputStream os = newFileOutputStream(stream);6 final OutputStreamWriter writer = newOutputStreamWriter(os);7 final Semaphore semaphore = new Semaphore(10);8 ExecutorService exec =Executors.newCachedThreadPool();9
10 final long start =System.currentTimeMillis();11 for (int i = 0; i < 10000000; i++) {12 final int num =i;13 Runnable task = newRunnable() {14 @Override15 public voidrun() {16 try{17 semaphore.acquire();18 wri