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();
      }


    }

  • 相关阅读:
    1002. Find Common Characters查找常用字符
    338. Counting Bits_比特位计数_简单动态规划
    Rail_UVa514_栈
    784. Letter Case Permutation C++字母大小写全排列
    C语言实现哈夫曼编码(最小堆,二叉树)
    559. Maximum Depth of N-ary Tree C++N叉树的最大深度
    27. Remove Element C++移除元素
    26. Remove Duplicates from Sorted Array C++ 删除排序数组中的重复项
    linux软件源配置
    linux 下安装 maven
  • 原文地址:https://www.cnblogs.com/smallfa/p/14620718.html
Copyright © 2011-2022 走看看