作者: 杨彪 时间: 2012-8-16 00:51
class InputOutputDemo1 {
public static void main(String[] args) {
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
// System.out.println("Hello World!");
}
}
class Res// 定义资源
{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable// 定义类Input实现Runnable接口
{
private Res r;
Input(Res r) {
this.r = r;
}
public void run()//覆盖run方法
{
int x=0;
while(true)
{
synchronized(r)
{
if(r.flag)
try{r.wait();}catch(Exception e){}//等待机制