欢迎来到我的博客

等待唤醒机制

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

 

posted @ 2017-10-18 10:02  Mr_Bean  阅读(153)  评论(0编辑  收藏  举报