线程同步互斥通信问题之互斥

线程同步互斥通信问题之互斥

使用wait()和notify()实现线程之间的通信。
要用到同步锁、同一数据或者同一算法的方法都尽量放在同一个类中:程序的健壮性、高类聚

在这里插入图片描述
实现代码如下:

package martina.TraditionalThread;

public class TraditionalThreadCommunication {
    final static Business business=new Business();
    public static void main(String[] agrs){
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<20;i++){
                   business.sub(i);
                }
            }
        }).start();
        
        for(int i=0;i<20;i++){
            business.main(i);
        }
    }

    /**
     * 一般来说我们的 锁要加在资源类中,而不是加在线程方法中
     */
    static class Business{
        //isToBeSub设置为true,则先循环sub()
        //否则 先执行main方法
        private boolean isToBeSub=true;
        public synchronized void main(int i){
            while(isToBeSub){
                try{
                    this.wait();
                }catch(InterruptedException e){
                    System.out.println("Main Error:"+e.toString());
                }
            }
            for(int j=0;j<10;j++){
                System.out.println("main thread of sequence of"+j+",loop of "+i);
            }
            isToBeSub=true;
            //将isToBeSub设置为true之后,去唤醒sub()方法
            this.notify();
        }
        public synchronized void sub(int i){
            //这里用if或者while都可以 建议用while,因为有一个伪唤醒的操作,可能会在没有被notified的时候就直接被唤醒了,导致互斥出错
            while(!isToBeSub){
                try{
                   this.wait();
                }catch(InterruptedException e){
                    System.out.println("Sub Error:"+e.toString());
                }
            }
            for(int j=0;j<5;j++){
                System.out.println("sub thread of sequence of"+j+",loop of "+i);
            }
            isToBeSub=false;
            //将isToBeSub设置为false之后,去唤醒main()方法
            this.notify();
        }
    }
}

实现效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mulinsen77/article/details/84341278
今日推荐