Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6099322
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类: Java

2013-12-06 03:17:11

原文地址:java多线程编程(2) 作者:hiyachen

接:java多线程编程(1)

将SellForm类作如下改动:

package atest.myThread;

/**
 * 产品属性及交互类
 * @author
 * @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的值来把自
    己挂起。即连续执行自己是不行的。两者互为唤醒。

阅读(690) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~