1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 import java.util.concurrent.CountDownLatch;
18 
19 /**
20  * Make sure that a sub-thread can join the main thread.
21  */
22 public class Main {
main(String[] args)23     public static void main(String[] args) throws Exception {
24         Thread t;
25         CountDownLatch waitLatch = new CountDownLatch(1);
26         CountDownLatch progressLatch = new CountDownLatch(1);
27 
28         t = new Thread(new JoinMainSub(Thread.currentThread(), waitLatch, progressLatch), "Joiner");
29         System.out.print("Starting thread '" + t.getName() + "'\n");
30         t.start();
31 
32         waitLatch.await();
33         System.out.print("JoinMain starter returning\n");
34         progressLatch.countDown();
35 
36         // Keep the thread alive a little longer, giving the other thread a chance to join on a
37         // live thread (though that isn't critically important for the test).
38         Thread.currentThread().sleep(500);
39     }
40 }
41 
42 class JoinMainSub implements Runnable {
43     private Thread mJoinMe;
44     private CountDownLatch waitLatch;
45     private CountDownLatch progressLatch;
46 
JoinMainSub(Thread joinMe, CountDownLatch waitLatch, CountDownLatch progressLatch)47     public JoinMainSub(Thread joinMe, CountDownLatch waitLatch, CountDownLatch progressLatch) {
48         mJoinMe = joinMe;
49         this.waitLatch = waitLatch;
50         this.progressLatch = progressLatch;
51     }
52 
run()53     public void run() {
54         System.out.print("@ JoinMainSub running\n");
55 
56         try {
57             waitLatch.countDown();
58             progressLatch.await();
59             mJoinMe.join();
60             System.out.print("@ JoinMainSub successfully joined main\n");
61         } catch (InterruptedException ie) {
62             System.out.print("@ JoinMainSub interrupted!\n");
63         }
64         finally {
65             System.out.print("@ JoinMainSub bailing\n");
66         }
67     }
68 }
69