您的位置:首页 > 编程语言 > Java开发

简单生产消费模式的代码流程(Java代码)

2016-12-11 16:00 459 查看
Student
package july.star.thread12;
/**
* Student
* @author MoXingJian
* @email 939697374@qq.com
* @date 2016年11月30日 下午3:39:45
* @version 1.0
*/
public class Student {
//定义成员变量
String name;
Integer age;
boolean flag;

}

GetThread
package july.star.thread12;
/**
* GetThread
*
* @author MoXingJian
* @email 939697374@qq.com
* @date 2016年11月30日 下午3:42:05
* @version 1.0
*/
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
//1、没数据,flag默认为false,进来
if (!s.flag) {
try {
//2  :等待时释放锁
s.wait();   //10、回到这里继续执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//11、输出结果
System.out.println(s.name + ":" + s.age);
//标记
s.flag = false;  //12、标记并唤醒
//唤醒
s.notify();
//13、抢占执行权
}
}
}
}

SetThread
package july.star.thread12;
/**
* SetThread
*
* @author MoXingJian
* @email 939697374@qq.com
* @date 2016年11月30日 下午3:40:31
* @version 1.0
*/
public class SetThread implements Runnable {
private Student s;
private int count;
public SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
//3:没数据,为false,不走wait()
if (s.flag) {
try {
s.wait();  //9、等待并释放锁,转到GetThread执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}

if (count % 2 == 0) {
s.name = "一菲";   //4、赋值
s.age = 21;
count++;
} else {
s.name = "二姐";
s.age = 28;
count++;
}

//修改标记
s.flag = true;  //6
//唤醒
s.notify();  //7、唤醒
}
//8、
//抢占CPU执行权,SetThread有或GetThread有权执行
//假设SetThread又抢到了
}
}
}

TestThread
package july.star.thread12;
/**
* 简单生产消费模式
* @author MoXingJian
* @email 939697374@qq.com
* @date 2016年11月30日 下午3:43:19
* @version 1.0
*/
public class TestThread {
public static void main(String[] args) {
//创建对象
Student s = new Student();

//创建线程
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);

Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
//开启线程
t1.start();
t2.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: