子线程和 主线程 互换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package demo;
 
/**
 * 子线程循环5次,主线程循环10次。依次交替。整个交替循环3次
 *
 */
public class ThreadTest {
    public static void main(String[] args) {
        init();
    }
     
    static void init(){
        final Print p = new Print();//封装了 循环的动作
        new Thread(new Runnable(){
 
            @Override
            public void run() {
                for(int i=0;i<3;i++){
                        p.subPrint(5);//循环5次
                    }
                }
        }).start();
         
        new Thread(new Runnable(){
             
            @Override
            public void run() {
                for(int i=0;i<3;i++){
                    p.mainPrint(10);//循环10次
                }
            }
             
        }).start();
    }
 
}

  

Print:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package demo;
 
/**
 * 两个方法之间互斥 (方法里面完整执行完),用 Sflag实现 开关控制 两个方法的切换
 *
 */
public class Print {
    boolean Sflag = true;
    public synchronized void subPrint(int num){
        while(!Sflag){//避免 伪唤醒
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for(int i=1;i<=num;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
        Sflag = false;
        this.notifyAll();
    }
    public synchronized void mainPrint(int num){
        while(Sflag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for(int i=1;i<=num;i++){
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
        Sflag = true;
        this.notifyAll();
    }
 
}

  

posted @   K____K  阅读(358)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示