您的位置:首页 > 其它

0015-多线程-生产消费模式

2018-02-09 01:07 232 查看
生产消费模式* 生产者生产包子
* 先看是否有包子,没有就生产,有就等待并通知消费者来消费包子
* 消费者消费包子
* 先看是否有包子,有就消费,没有就等待并通知生产者来生产包子
* java提供了等待唤醒机制等待唤醒机制* Object类提供了等待方法和唤醒方法
* 等待
* wait():进入等待并立即释放锁,等待期间该线程抢不到cpu执行权
* 唤醒
* notify():唤醒绑定在该锁上的单个等待的线程,重新抢cpu执行权
* notifyAll():唤醒绑定在该锁上的所有等待的线程,重新抢cpu执行权
* 这些方法必须使用锁对象调用,所以定义在Object类中等待唤醒机制代码
* Student类
* SetThread类:生产者
* GetThread类:消费者
* MyTest类:测试类
Student类package pack;

public class Student {
private String name;
private int age;
private boolean flag;

public synchronized void set(String name, int age) {
if(this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 生产
this.name = name;
this.age = age;
// 修改标记
this.flag = true;
this.notify();
}

public synchronized void get(){
if(!this.flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 消费
System.out.println(this.name+"---"+this.age);
// 修改标记
this.flag=false;
this.notify();
}
}
SetThread类
package pack;

public class SetThread implements Runnable {
private Student s;
private int x = 0;

public SetThread(Student s) {
this.s = s;
}

@Override
public void run() {
while (true) {
if (x % 2 == 0) {
s.set("刘亦菲", 25);
} else {
s.set("范守俊", 28);
}
x++;
}
}

}
GetThread类package pack;

public class GetThread implements Runnable {

private Student s;

public GetThread(Student s) {
this.s = s;
}

@Override
public void run() {
while (true) {
s.get();
}
}
}MyTest    package pack;

public class MyTest {
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: