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 } */ }

 

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

 

posted @ 2016-11-04 02:01  wq3435  阅读(226)  评论(0编辑  收藏  举报