/*
等待/唤醒机制
涉及方法:Lock的应该用
1.await(): 挣线程处于冻结状态,被wait的线程存储到线程池中
2.signal():唤醒线程池中的一个线程(任意唤醒一个)
3.signalAll():唤醒线程中的所有线程。
这些方法都必须定义在同步中因为:这些方法都是用于操作线程状态的方法,必须要明确到底操作的是哪个锁上的线程
*/
//创建资源
import java.util.concurrent.locks.*;
class Person
{
private String name;
private String sex;
boolean bl = false;
Lock lock = new ReentrantLock();//创建一个锁对象
Condition in_cn = lock.newCondition();
Condition out_cn = lock.newCondition();
public void set(String name ,String sex)
{
lock.lock();
while(bl)
{
try{in_cn.wait();}catch(InterruptedException e){}
}
this.name = name;
this.sex =sex;
this.bl = true;
out_cn.signal();;
lock.unlock();
}
public void out()
{
lock.lock();
while(!bl)
try{out_cn.wait();}catch(InterruptedException e){}
System.out.println("姓名:"+this.name+"性别:"+this.sex);
bl = false;
in_cn.signal();
lock.lock();
}
}
//创建一个输出对象
class InputDemo implements Runnable
{
private boolean flag= true;
Person p;
InputDemo(Person p)
{
this.p=p;
}
public void run()
{
while(true)
{
if(flag)
{p.set("小强","男");flag=false;}
else{p.set("弱弱","女");flag=true;}
}
}
}
//创建一个输出对象
class Output implements Runnable
{
Person p ;
Output(Person p)
{
this.p = p;
}
public void run()
{
while(true){
p.out();
}
}
}
class ThReenTrant
{
public static void main(String[] args)
{
Person p = new Person();
InputDemo in = new InputDemo(p);
Output out = new Output(p);
Thread t = new Thread(in);
Thread t1 = new Thread(in); //两个访问者
Thread t2 = new Thread(out);
Thread t3 = new Thread(out); //两个输出者
t.start();
t1.start();
t2.start();
t3.start();
}
}
|
|