编辑器:Notepad++;学习视频:毕向东Java基础教程
等待唤醒机制的经典问题:多生产多消费
停止线程的方式
/*
* 等待唤醒机制中的经典问题 *
****** 多生成产多消费示例 ******
* 多个线程操作同一资源,任务不同,使用相同的锁 *
*/
import java.util.concurrent.locks.*;
//定义资源
class Source3 //资源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.signalAll(); //全部唤醒,避免死锁(都处于等待状态)
}
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.signalAll();
}
finally
{
lock.unlock();
}
}
}
//定义任务1,负责输入姓名和年龄
class Input3 implements Runnable
{
//为保证不同线程操作同一资源,这里不要实例化资源,而是以参数形式传递给构造函数
Source3 s;
Input3(Source3 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 Output3 implements Runnable
{
Source3 s;
Output3(Source3 s)
{
this.s = s;
}
public void run()
{
while(true)
{
s.getInfo();
}
}
}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
//创建资源
Source3 s = new Source3();
//创建任务
Input3 in1 = new Input3(s);
Input3 in2 = new Input3(s);
Output3 out1 = new Output3(s);
Output3 out2 = new Output3(s);
//创建线程
Thread t0 = new Thread(in1);
Thread t1 = new Thread(in2);
Thread t2 = new Thread(out1);
Thread t3 = new Thread(out2);
//开启线程
t0.start();
t1.start();
t2.start();
t3.start();
}
}