//多线程通讯
//多个线程处理同一资源,但是任务不同
//等待唤醒方法:
//wait():将线程变成为冻结状态,线程会被存储在线程池中;
//notify():唤醒线程中的一个线程(任意的)
//notifyAll():唤醒所有线程;
/**************************************************************/
//建立资源类
class Resource
{
private boolean flag = false;
private String name;
private String sex;
public synchronized void set(String name,String sex)
{
if(flag)
try
{
this.wait();
}
catch (InterruptedException e)
{
}
this.name = name;
this.sex = sex;
this.flag=true;
this.notify();
}
public synchronized void get()
{
if(!this.flag)
try
{
this.wait();
}
catch (InterruptedException e)
{
}
System.out.println(name+"--"+sex);
this.flag=false;
this.notify();
}
}
//建立输入任务类
class Input implements Runnable
{
Resource r;
Input(Resource r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
if (x==0)
{
r.set("野兽","男 ");
}
else
{
r.set("meinv","nv ");
}
x=(x+1)%2;
}
}
}
//建立输出任务类
class Output implements Runnable
{
Resource r;
Output(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
r.get();
}
} }
} class IoDemo1
{
public static void main(String[] args)
{
//建立资源对象
Resource r = new Resource();
//建立输入任务对象
Input in = new Input(r);
//建立输出任务对象
Output out = new Output(r);
//建立输入任务的进程
Thread t1 = new Thread(in);
//建立输出任务的进程
Thread t2 = new Thread(out);
//开启线程
t1.start();
t2.start();
}
}