编辑器:Notepad++;学习视频:毕向东Java基础教程
/*
Lock示例,优化WaitNotifyDemo代码,提高效率
多个线程操作同一资源,任务不同,使用相同的锁
一个Lock对象,可以绑定多组Condition实例
确保每输入一项,就相应的输出一项
*/
import java.util.concurrent.locks.*;
//定义资源
class Source2 //资源1,包含一些人的姓名和性别
{
private String name;
private String sex;
boolean flag = false; //一般都会定义标志位
Lock lock = new ReentrantLock();
Condition locka = lock.newCondition();
Condition lockb = lock.newCondition();
public void getInfo()
{
lock.lock(); //显示操作锁
try
{
while(!flag)
try{lockb.await();}catch(InterruptedException e){} //每次唤醒都会判断flag,确定是否输出
System.out.println(Thread.currentThread().getName()+"...Output...name= "+name+"...Output..sex= "+sex);
System.out.println();
flag = false;
locka.signal(); //唤醒对方
}
finally
{
lock.unlock();
}
}
public void setInfo(String name,String sex)
{
lock.lock();
try
{
while(flag)
try{locka.await();}catch(InterruptedException e){} //每次唤醒都会判断flag,确定是否输入
this.name = name;
this.sex = sex;
//打印输入内容
System.out.println(Thread.currentThread().getName()+"...Input....name= "+name+"...Input...sex= "+sex);
flag = true;
lockb.signal(); //唤醒对方
}
finally
{
lock.unlock();
}
}
}
//定义任务1,负责输入姓名和年龄
class Input2 implements Runnable
{
//为保证不同线程操作同一资源,这里不要实例化资源,而是以参数形式传递给构造函数
Source2 s;
Input2(Source2 s)
{
this.s = s;
}
//覆盖run方法
public void run()
{
int x = 0;
while(true)
{
if(x==0)
{
s.setInfo("mike","man");
}
else
{
s.setInfo("花花","***famale***");
}
x = (x+1)%2; //0,1切换机制
}
}
}
//定义任务2,负责输出姓名和年龄
class Output2 implements Runnable
{
Source2 s;
Output2(Source2 s)
{
this.s = s;
}
public void run()
{
while(true)
{
s.getInfo();
}
}
}
class LockDemo
{
public static void main(String[] args)
{
//创建资源
Source2 s = new Source2();
//创建任务
Input2 in = new Input2(s);
Output2 out = new Output2(s);
//创建线程
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//开启线程
t1.start();
t2.start();
}
}
运行结果: