// author:liu_zl
1 public class CountDownLatchActivity extends Activity implements OnClickListener{
2 @Override
3 protected void onCreate(Bundle savedInstanceState) {
4 // TODO Auto-generated method stub
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.latch_activity);
7 //定义countDownLatch, 计数为2:表示有两个线程
8 CountDownLatch countDownLatch = new CountDownLatch(2);
9 MyThread myThread1 = new MyThread(countDownLatch,"myThread1");
10 MyThread myThread2 = new MyThread(countDownLatch, "myThread2");
11 // 开启两个子线程
12 myThread1.start();
13 myThread2.start();
14 try {
15 //主线程等待
16 countDownLatch.await();
17 endWork();
18 } catch (InterruptedException e) {
19 // TODO Auto-generated catch block
20 e.printStackTrace();
21 }
22
23 }
24 public void onClick(View v) {
25 }
26
27 /*
28 * 子线程执行完毕,主线程执行的方法
29 */
30 private void endWork() {
31 System.out.println("end work");
32 }
33
34 class MyThread extends Thread {
35 private CountDownLatch countDownLatch;
36 private String nameString;
37 public MyThread(CountDownLatch countDownLatch, String name) {
38 this.countDownLatch = countDownLatch;
39 this.nameString = name;
40 }
41 @Override
42 public void run() {
43 // TODO Auto-generated method stub
44 doWorking();
45 countDownLatch.countDown(); //计数减一,直到计数为零
46 complete();
47 super.run();
48 }
49 /**
50 * 子线程开始执行
51 */
52 private void doWorking() {
53 System.out.println(nameString+"\t do working");
54 }
55
56 /**
57 * 子线程执行结束
58 */
59 private void complete() {
60 System.out.println(nameString+"\t completed");
61 }
62 }
63
64
65 }