多线程 04 传统线程同步通信技术

面试题:子线程循环10次,接着主线程循环循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环10次,请写出程序;

思路:先保证我干的时候你不到扰我,你干的时候我不打扰你,再看你一下我一下。

public class TraditionalCommunication {

    public static void main(String[] args){

        new Thread(

                new Runnable() {

                    @Override

                    public void run() {

                        for (int i=0;i<=50;i++){

                            synchronized (TraditionalCommunication.class){

                                for(int j=0;j<10;j++){

                                    System.out.println("sub thread sequence of "+j+" of loop "+i);

                                }

                            }

                        }

                    }

                }

        ).start();

        for (int i=0;i<=50;i++){

            synchronized (TraditionalCommunication.class){

                for(int j=0;j<100;j++){

                    System.out.println("main thread sequence of "+j+" of loop "+i);

                }

            }

        }

    }

}

优化(使用面向对象的思想,将有关联的方法集中到一个类中,方便维护和更改。高内聚低耦合;):

总结:同步+通信;(好的设计会达到点睛的效果),注意互斥的锁或者通信是放在资源上面的而不是放在线程上面的。(注意synchronized用什么对象,那么wait就用什么对象);while比if更好,while可以防假唤醒。

public class TraditionalCommunication {

    public static void main(String[] args){

        final Bussiness bussiness = new Bussiness();

        new Thread(

                new Runnable() {

                    @Override

                    public void run() {

                        for (int i=0;i<=50;i++){

                            bussiness.sub(i);

                        }

                    }

                }

        ).start();

        for (int i=0;i<=50;i++){

            bussiness.main(i);

        }

    }

     static class Bussiness{

        private Boolean shouldSub=true;

        public synchronized void main(int i){

            while(shouldSub){//if

                try {

                    this.wait();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

            for(int j=0;j<100;j++){

                System.out.println("main thread sequence of "+j+" of loop "+i);

            }

            shouldSub=true;

            this.notify();

        }

        public synchronized void sub( int i){

            while(!shouldSub){

                try {

                    this.wait();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

            for(int j=0;j<10;j++){

                System.out.println("sub thread sequence of "+j+" of loop "+i);

            }

            shouldSub=false;

            this.notify();

        }

    }

}

如有疑问,请发邮件:[email protected]

github:  https://github.com/wangrui0/