doclist 阅读(123) 评论(0)
接:java多线程编程(1)

将SellForm类作如下改动:

package atest.myThread;

/**
 * 产品属性及交互类
 * @author chf@tsinghua.org.cn
 * @version $Revision$
 */
public class SellForm {

    int productNum;

    boolean boolSwitch = false;

    // customer
    synchronized public int getProductNum() {
        System.out.println("Customer.getProductNum():boolSwitch=" + boolSwitch);
        if (!boolSwitch){
            try {
                System.out.println("Customer.getProductNum():wait()");
                wait();
            } catch (InterruptedException e) {
                // TODO 自動生成された catch ブロック
                //e.printStackTrace();
                System.out.println("Exception: InterruptedException");
            }
        }

        System.out.println("Customer:" + productNum);
        boolSwitch = false;
        notify();
        return productNum;
    }

    // produce
    synchronized public void setProductNum(int productNum) {

        System.out.println("Producer.setProductNum():boolSwitch=" + boolSwitch);
        if (boolSwitch){
            try {
                System.out.println("Producer.setProductNum():wait()");
                wait();
            } catch (InterruptedException e) {
                // TODO 自動生成された catch ブロック
                //e.printStackTrace();
                System.out.println("Exception: InterruptedException");
            }
        }
        this.productNum = productNum;
        System.out.println("Producer:" + productNum);
        boolSwitch = true;
        notify();
    }
}

http://hiyachen.blog.chinaunix.net
总结:
1:因为boolean boolSwitch = false;即boolSwitch的初始值是false.
     所以最初的Customer被挂起,等待Producer把boolSwitch = true.
     即boolSwitch的初始值决定了Customer和Producer的执行顺序。
2:Customer和Producer的执行结束后,都通过改变boolSmitch的值来把自
    己挂起。即连续执行自己是不行的。两者互为唤醒。