jdk1.5中java.util.concurrent包编写多线程(二)

 

当然线程池也要显式退出了。

package concurrent;

import java.io.File;

import java.io.FileFilter;

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.LinkedBlockingQueue;

import java.util.concurrent.atomic.AtomicInteger;

public class TestBlockingQueue {

static long randomTime() {

    return (long) (Math.random() * 1000);

}

public static void main(String[] args) {

    // 能容纳100个文件

    final BlockingQueue<File> queue = new LinkedBlockingQueue<File>(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 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(".java");

          }

          });

          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++) {

      // write thread

      final int NO = index;

      Runnable write = 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(write);

    }

    exec.shutdown();

}

}

 

从名字可以看出,CountDownLatch是一个倒数计数的锁,当倒数到0时触发事件,也就是开锁,其他人就可以进入了。在一些应用场合中,需要等待某个条件达到要求后才能做后面的事情;同时当线程都完成后也会触发事件,以便进行后面的操作。

CountDownLatch最重要的方法是countDown()await(),前者主要是倒数一次,后者是等待倒数到0,如果没有到达0,就只有阻塞等待了。

一个CountDouwnLatch实例是不能重复使用的,也就是说它是一次性的,锁一经被打开就不能再关闭使用了,如果想重复使用,请考虑使用CyclicBarrier

下面的例子简单的说明了CountDownLatch的使用方法,模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。

同样,线程池需要显式shutdown

package concurrent;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class TestCountDownLatch {

public static void main(String[] args) throws InterruptedException {

    // 开始的倒数锁

    final CountDownLatch begin = new CountDownLatch(1);

    // 结束的倒数锁

    final CountDownLatch end = new CountDownLatch(10);

    // 十名选手

    final ExecutorService exec = Executors.newFixedThreadPool(10);

    for(int index = 0; index < 10; index++) {

      final int NO = index + 1;

      Runnable run = new Runnable(){

        public void run() {

          try {

            begin.await();

            Thread.sleep((long) (Math.random() * 10000));

            System.out.println("No." + NO + " arrived");

          } catch (InterruptedException e) {

          } finally {

            end.countDown();

          }

        }

      };

      exec.submit(run);

    }

    System.out.println("Game Start");

    begin.countDown();

    end.await();

    System.out.println("Game Over");

    exec.shutdown();

}

} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值