开发者社区> 问答> 正文

设计四个线程对象,两个线程执行减操作,两个线程执行加操作。

设计四个线程对象,两个线程执行减操作,两个线程执行加操作。

展开
收起
游客pklijor6gytpx 2019-11-21 14:59:00 874 0
1 条回答
写回答
取消 提交回答
  • privateintdata=10;//初始值
    privatebooleanflag=true;
    publicsynchronizedvoidadd(){//加法操作
    if(this.flag==false){//已经生产过了,不能生产
    try{
    super.wait();//等待
    }catch(InterruptedExceptione){
    e.printStackTrace();
    }
    }
    try{
    Thread.sleep(200);
    }catch(InterruptedExceptione){
    e.printStackTrace();
    }
    System.out.println("加法操作:"+this.data++);
    this.flag=false;//已经生产完成,修改标志位
    super.notify();//唤醒等待线程
    }
    publicsynchronizedvoidsubtract(){//减法操作
    if(this.flag==true){//未生产,不能取走
    try{
    super.wait();//等待
    }catch(InterruptedExceptione){
    e.printStackTrace();
    }
    }
    try{
    Thread.sleep(100);
    }catch(InterruptedExceptione){
    e.printStackTrace();
    }
    System.out.println("减法操作:"+this.data--);
    this.flag=true;//已经取走了,可以继续生产
    super.notify();//唤醒等待线程
    }
    //setter、getter略
    }
    classAdditionimplementsRunnable{//定义生产者
    privateMessagemsg=null;
    publicAddition(Messagemsg){
    this.msg=msg;
    }
    @Override
    publicvoidrun(){
    for(intx=0;x<50;x++){//加法执行50次
    this.msg.add();//加法操作
    }
    }
    }
    classSubtractionimplementsRunnable{//定义消费者
    privateMessagemsg=null;
    publicSubtraction(Messagemsg){
    this.msg=msg;
    }
    @Override
    publicvoidrun(){
    for(intx=0;x<50;x++){//减法执行50次
    this.msg.subtract();//执行减法
    }
    }
    }
    publicclassTestDemo{
    publicstaticvoidmain(Stringargs[]){
    Messagemsg=newMessage();
    newThread(newAddition(msg),"加法对象A").start();//启动线程
    newThread(newAddition(msg),"家访对象B").start();//启动者线程
    newThread(newSubtraction(msg),"减法对象A").start();//取得线程
    newThread(newSubtraction(msg),"减法对象B").start();//取得线程
    }
    }
    
    2019-11-21 14:59:34
    赞同 展开评论 打赏
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
多IO线程优化版 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多