zoukankan      html  css  js  c++  java
  • 等待唤醒机制

    package com.demo;

    public class Test {
    public static void main(String[] args) {
    Resource resource = new Resource();
    Input input = new Input(resource);
    Output output = new Output(resource);
    Thread t1 = new Thread(input);
    Thread t2 = new Thread(output);
    t1.start();
    t2.start();
    }
    }

    class Resource {
    private String name;
    private String sex;
    private boolean flag;

    public synchronized void set(String name, String sex) throws InterruptedException {
    if(this.flag)
    this.wait();
    this.name = name;
    this.sex = sex;
    this.flag = true;
    this.notify();
    }

    public synchronized void print() throws InterruptedException {
    if(!flag)
    this.wait();
    System.out.println(name + " " + sex);
    this.flag = false;
    this.notify();
    }
    }

    class Input implements Runnable{
    private Resource r;

    public Input(Resource r) {
    this.r = r;
    }

    @Override
    public void run() {
    int i = 0;
    while(true) {
    try {
    if(i % 2 == 0) {
    r.set("Tom", "男");
    } else {
    r.set("Mary", "女");
    }
    i++;
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }

    class Output implements Runnable{
    Resource r;
    public Output(Resource r) {
    this.r = r;
    }
    @Override
    public void run() {
    while(true) {
    try {
    r.print();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }

  • 相关阅读:
    ButterKnife 原理解析
    有关java之反射的使用
    Integer 与 int 中的 ==
    下拉框、多选框、单选框 通过TagHelper绑定数据
    动态构建视图表单
    添加我的应用中的后台图标
    标准服务接口示例代码
    .net Core下的 常用方法
    使用Redirect跳转
    标准表单提交示例代码
  • 原文地址:https://www.cnblogs.com/bean/p/7685268.html
Copyright © 2011-2022 走看看