子线程和主线程业务依次执行循环50次


子线程业务:循环10次
java

主线程业务:循环20次算法


这两个循环(业务)须要交替执行共50次
app


要用到共同数据的(包括同步锁)或共同算法(加密解密)的若干个方法应该归在同一个类上,这种设计正好体现了高内聚和程序的健壮性
ide


 while (bShouldSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

中使用while防止假唤醒,使用if就不行oop

虚假唤醒就是一些obj.wait()会在除了obj.notify()和obj.notifyAll()的其余状况被唤醒,而此时是不该该返回的,因此要加条件判断。this

synchronized (obj) {  
         while (<condition does not hold>)  
             obj.wait();  
         ... // Perform action appropriate to condition  
     }


public class TraditionalThreadCommunication {
    final Business business = new Business();

    public static void main(String[] args) {

            new TraditionalThreadCommunication().init();
        
    }

    private void init()  {

        new Thread(new Runnable() {

            @Override
            public void run() {

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

                    business.sub(i);

                }
            }
        }).start();

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

            business.main(i);
        }

    }

    //业务对象
    class Business {
        private boolean bShouldSub = true;

        public synchronized void sub(int i) {
            while (!bShouldSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

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

                System.out.println("sub thread sequence of" + j + ",loop of "
                        + i);
            }
            bShouldSub = false;
            this.notify();
        }

        public synchronized void main(int i) {

            while (bShouldSub) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for (int j = 1; j <= 20; j++) {

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

            bShouldSub = true;
            this.notify();
        }

    }

}


使用lock和condition改写代码加密

http://tianxingzhe.blog.51cto.com/3390077/1716805
线程

相关文章
相关标签/搜索