zoukankan      html  css  js  c++  java
  • 多线程 input生产 res(username,sex) out消费 synchronized(res) wait-notify

    1、wait 使用说明

    public class Thread001 {


    class Res{
    public String userName;
    private char sex;
    private boolean flag;
    }

    class InputThread extends Thread{

    Res res;

    public InputThread(Res res) {
    this.res=res;
    }

    @Override
    public void run() {
    int count=0;
    while (true){
      synchronized (res){
        try {
          if(res.flag)//true
          {
            res.wait();
          }
          }catch (Exception e){

        }
        if(count==0){
          res.userName="胜军";
          res.sex='男';
        }else {
          res.userName="小君";
          res.sex='女';
        }
        res.flag=true;
        //唤醒消费者线程, 就绪状态被cpu调度为运行状态
        res.notify();
        count=(count+1)%2;
      }
     }
    }


    }

    class OutThread extends Thread{
      Res res;
      public OutThread(Res res) {
        this.res=res;
      }

      @Override
      public void run() {
        while (true){
          synchronized (res){
            try {
              if(!res.flag){//flag=false
              //当线程变为阻载状态,同时释放锁
              res.wait();
            }
            }catch (Exception e){

            }


          System.out.println(res.userName+","+res.sex);
          res.flag=false;
          //唤醒写的线程
          res.notify();
        }
         }
      }


    }


      public void start(){
        Res res=new Res();
        //写线程
        new InputThread(res).start();
        //读的线程
        new OutThread(res).start();
        //锁对象Res
      }


      public static void main(String[] args){
        new Thread001().start();
      }


    }

  • 相关阅读:
    【重温设计模式】之005单例模式
    【重温设计模式】之004抽象工厂模式
    【重温设计模式】之003工厂方法模式
    【重温设计模式】之002简单工厂模式
    【重温设计模式】之001概述
    【工具】之003-Windows下常用工具
    【工具】之002-Mac下常用工具
    【工具】之001-CentOS7 最小化安装配置
    做人要精致,做事要靠谱
    Vue+Vue-router微信分享功能
  • 原文地址:https://www.cnblogs.com/smallfa/p/14620718.html
Copyright © 2011-2022 走看看