Java多線程,線程交替執行


兩個線程,一個打印1-100的奇數,一個打印1-100的偶數;要求:線程1打印5個之后,線程2開始打印,線程2打印5個之后,線程1再開始打印,以此循環。

Code:

package com.qhong;


public class Main {
    /*
       * 兩個線程,一個打印1-100的奇數,一個打印1-100的偶數;要求:線程1打印5個之后,線程2開始打印,線程2打印5個之后,線程1再開始打印,以此循環。
       */
    private static int state = 1;
    private static int num1 = 1;
    private static int num2 = 2;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final Main t=new Main();
        new Thread(new Runnable(){
            @Override
            public void run(){
                while(num1<100){
                    //兩個線程都用t對象作為鎖,保證每個交替期間只有一個線程在打印
                    synchronized(t){
                        // 如果state!=1, 說明此時尚未輪到線程1打印, 線程1將調用t的wait()方法, 直到下次被喚醒
                        if(state!=1){
                            try{
                                t.wait();
                            }catch(InterruptedException e){
                                e.printStackTrace();
                            }
                        }
                        // 當state=1時, 輪到線程1打印5次數字
                        for(int j=0;j<5;j++){
                            System.out.println(num1);
                            num1 +=2;
                        }
                        // 線程1打印完成后, 將state賦值為2, 表示接下來將輪到線程2打印
                        state = 2;
                        // notifyAll()方法喚醒在t上wait的線程2, 同時線程1將退出同步代碼塊, 釋放t鎖
                        t.notifyAll();
                    }
                }
            }
        }).start();

        new Thread(new Runnable(){
            @Override
            public void run(){
                while(num2<100){
                    synchronized(t){
                        if(state!=2){
                            try{
                                t.wait();
                            }catch(InterruptedException e){
                                e.printStackTrace();
                            }
                        }

                        for(int i=0;i<5;i++){
                            System.out.println(num2);
                            num2 +=2;
                        }

                        state=1;
                        t.notifyAll();
                    }

                }
            }
        }).start();
    }
}

Output:

1
3
5
7
9
2
4
6
8
10
11
13
15
17
19
12
14
16
18
20
21
23
25
27
29
22
24
26
28
30
31
33
35
37
39
32
34
36
38
40
41
43
45
47
49
42
44
46
48
50
51
53
55
57
59
52
54
56
58
60
61
63
65
67
69
62
64
66
68
70
71
73
75
77
79
72
74
76
78
80
81
83
85
87
89
82
84
86
88
90
91
93
95
97
99
92
94
96
98
100
View Code

 

http://blog.csdn.net/junli_chen/article/details/49584187


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM