JDK1.5的新特性:提供了线程升级解决方案
1.Lock代替了synchronized
2.Condition代替了Object监视器方法,将(wait,notify,notifyAll)封装成Condition对象,Condition对象可以生成多个,也就是说可以有多组(wait,notify,notifyAll),可以调用唤醒对方的函数
3.该对象可以通过Lock锁进行获取。
import java.util.concurrent.locks.*;
class Res
{
private String name;
private String sex;
boolean flag=false;
private Lock lock=new ReentrantLock();
private Condition condition_ru = lock.newCondition();
private Condition condition_chu = lock.newCondition();
public void setNum(String name,String sex)throws InterruptedException
{
lock.lock();
try
{
while(flag)
condition_ru.await();
this.name=name;
this.sex=sex;
flag=true;
condition_chu.signal();
}
finally
{
lock.unlock();
}
}
public void out()throws InterruptedException
{
lock.lock();
try
{
while(!flag)
condition_chu.await();
System.out.println(name+"----"+sex);
flag=false;
condition_ru.signal();
}
finally
{
lock.unlock();
}
}
}
class Intput implements Runnable
{
private Res r;
Intput(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
try{
if(x==0)
r.setNum("zhoubin","men");
else
r.setNum("lili","women");
x=(x+1)%2;
}
catch(InterruptedException e){}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
try{
r.out();
}
catch(InterruptedException e){}
}
}
}
class Demo
{
public static void main(String[] args)
{
Res r=new Res();
new Thread(new Intput(r)).start();
new Thread(new Output(r)).start();
//new Thread(new Output(r)).start();
//new Thread(new Output(r)).start();
/*
Intput in=new Intput(r);
Output ou=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(ou);
t1.start();
t2.start();
*/
}
}
|
|