首页 > 代码库 > Java多线程与并发库高级应用-传统线程同步通信技术

Java多线程与并发库高级应用-传统线程同步通信技术

面试题:

子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着又 主线程循环100次,如此循环50次,请写出程序

/**
 * 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着又 主线程循环100次,如此循环50次,请写出程序
 * 
 * @author Administrator
 * 
 */
public class TraditionalThreadCommunication {

    public static void main(String[] args) {
        final Business business = new Business();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 50; i++) {
                    business.sub(i);
                }
            }
        }).start();

        for (int i = 1; i <= 50; i++) {
            business.main(i);
        }
    }

}

class Business {
    private boolean isShoudeSub = true;

    /**
     * 同步加在需要访问的资源的代码上,不要放在线程上
     * @param i
     */
    public synchronized void sub(int i) {
        while (!isShoudeSub) {   //这里也可以用 if ,用while比较好一些  As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop
            try {                // 防止线程有可能被假唤醒 (while放在这里提现了水准)
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int j = 1; j <= 100; j++) {
            System.out
                    .println("sub thread sequence of " + j + ", loop of " + i);
        }
        isShoudeSub = false;
        this.notify();
    }

    public synchronized void main(int i) {
        while (isShoudeSub) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int j = 1; j <= 10; j++) {
            System.out.println("main thread sequence of " + j + ", loop of "
                    + i);
        }
        isShoudeSub = true;
        this.notify();
    }
    /**
     * 
     * synchronized (obj) { 这里的obj与obj.wait必须相同,否则会抛异常
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }

     */
}

 

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

 

Java多线程与并发库高级应用-传统线程同步通信技术