Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6945885
  • 博文数量: 701
  • 博客积分: 10821
  • 博客等级: 上将
  • 技术积分: 12021
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-02 10:41
个人简介

中科院架构师,专注企业数字化各个方面,MES/ERP/CRM/OA、物联网、传感器、大数据、ML、AI、云计算openstack、Linux、SpringCloud。

文章分类

全部博文(701)

分类: Java

2013-11-27 14:38:05

接: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的值来把自
    己挂起。即连续执行自己是不行的。两者互为唤醒。

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