待的事情都已经发生。可以使用闭锁来这样设计程序达到目的:
1 public class CountDownLatchApproach { 2 public static void main(String[] args) throws IOException, InterruptedException { 3 final int nThreads = 10; 4 final CountDownLatch endGate = new CountDownLatch(nThreads); 5 final File stream = new File("c:\\temp\\stonefeng\\stream.txt"); 6 final OutputStream os = new FileOutputStream(stream); 7 final OutputStreamWriter writer = new OutputStreamWriter(os); 8 ExecutorService exec = Executors.newCachedThreadPool(); 9 for (int i = 0; i < nThreads; i++) { 10 final int num = i; 11 Runnable task = new Runnable() { 12 @Override 13 public void run() { 14 try { 15 writer.write(String.valueOf(num)+"\n"); 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } finally { 19 endGate.countDown(); 20 } 21 } 22 }; 23 exec.submit(task); 24 } 25 endGate.await(); 26 writer.write("---END---\n"); 27 writer.close(); 28 } 29 }
这种解决方案虽然可以达到目的但是性能差到没朋友,我更倾向于使用第一种方案。
现在我们有了更优雅的第三种方案,它的执行性能也不错。
1 public class MySemaphore { 2 3 public static void main(String[] args) throws IOException, InterruptedException { 4 final File stream = new File("c:\\temp\\stonefeng\\stream.txt"); 5 final OutputStream os = new FileOutputStream(stream); 6 final OutputStreamWriter writer = new OutputStreamWriter(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 = new Runnable() { 14 @Override 15 public void run() { 16 try { 17 semaphore.acquire(); 18 writer.write(String.valueOf(num)+"\n"); 19 semaphore.release(); 20 } catch (IOException e) { 21 e.printStackTrace(); 22 } catch (InterruptedException e) { 23 e.printStackTrace(); 24 } 25 } 26 }; 27 exec.submit(task); 28 } 29 exec.shutdown(); 30 exec.awaitTermination(1, TimeUnit.HOURS); 31 writer.write("---END---\n"); 32 writer.close(); 33 System.out.println("ËùÓеÄ×ÓÏ̶߳¼½áÊøÁË£¡"); 34 final long end = System.currentTimeMillis(); 35 System.out.println((end-start)/1000); 36 } 37
网友评论