/*
* 需求:两条线程,一条线程不断存储,学生的信息,还有一个线程不断打印学生信息。要求存一个打一个
* 思想:通过多线程唤醒机制实现
* 步骤:1.创建资源类,把学生数据封装到里面,并对外提供接口操作数据,
存在线程安全隐患的声明为同步函数
2.创建线程任务,使用资源对象初始化线程任务对象
3.创建线程,使用线程任务初始化
4.开启线程
*/
class Resocuce
{
private String name; //学生姓名
private boolean sex; //学生性别 false:男生,true:女生
private int num; //学生学号
private boolean flag = false; //标志位,用于标志数据是否有新的存储
//false:已存新数据,应该打印了
//true:新的数据已经打印了, 应该存储了
public synchronized void setInfo(String name, boolean sex, int num){
if(!flag){
try{
this.wait();
}
catch(InterruptedException e){}
}
this.name = name;
this.sex = sex;
this.num = num;
flag = false;
this.notify();
}
public synchronized void getInfo(){
if(flag){
try{
this.wait();
}
catch(InterruptedException e){}
}
System.out.println("name:" + name + ",sex:" + (sex ? "女":"男") + ",num:" + num);
flag = true;
this.notify();
}
}
class InputInfo implements Runnable
{
private Resocuce r;
InputInfo(Resocuce r){
this.r = r;
}
public void run(){
boolean flag = true;
while(true){
if(flag){
r.setInfo("xiaoli", true, 1303);
flag = !flag;
}else{
r.setInfo("mawang", false, 9103);
flag = !flag;
}
}
}
}
class OutputInfo implements Runnable
{
Resocuce r;
OutputInfo(Resocuce r){
this.r = r;
}
public void run(){
while(true)
r.getInfo();
}
}
class SyncThreadDemo
{
public static void main(String[] args)
{
//创建资源
Resocuce r = new Resocuce();
//创建任务
InputInfo in = new InputInfo(r);
OutputInfo out = new OutputInfo(r);
//创建线程
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//开启线程
t1.start();
t2.start();
}
}
Java-线程$等待唤醒机制(wait,notify)
最新推荐文章于 2024-08-29 13:45:35 发布