让两个线程顺序执行

 1 public class ThreadJoiner {
 2     public static void main(String[] args) {
 3         Object lock = new Object();
 4            
 5         Thread starterThread = new Thread(new StarterThread(lock));
 6         Thread enderThread = new Thread(new EnderThread(lock));
 7        
 8         starterThread.start();
 9         enderThread.start();
10     }
11 }
12 class StarterThread implements Runnable {
13 
14     private Object lock = null;
15    
16     public StarterThread(Object lock) {
17         this.lock = lock;
18     }
19 
20     public void run() {
21         System.out.println("start..");
22        
23         for(int i =0; i<10; i++){
24             System.out.println("start:"+i);
25         } 
26         synchronized(lock){
27             lock.notifyAll();
28         }
29     }
30 }
31 class EnderThread implements Runnable {
32     private Object lock = null;
33     public EnderThread(Object lock) {
34         this.lock = lock;
35     }
36 
37     public void run() {
38         synchronized(lock){
39             try {
40                 lock.wait();
41             } catch (InterruptedException e) {
42                 e.printStackTrace();
43             }
44         }
45         System.out.println("end..");
46         for(int i =0; i<10; i++){
47             System.out.println("end:"+i);
48         }  
49     }
50 }
51 /*
52 start..
53 start:0
54 start:1
55 start:2
56 start:3
57 start:4
58 start:5
59 start:6
60 start:7
61 start:8
62 start:9
63 end..
64 end:0
65 end:1
66 end:2
67 end:3
68 end:4
69 end:5
70 end:6
71 end:7
72 end:8
73 end:9
74 */

 

转载于:https://www.cnblogs.com/wanghui390/p/3443572.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值