黑马程序员技术交流社区
标题:
线程问题
[打印本页]
作者:
刘潘敏
时间:
2015-4-9 01:16
标题:
线程问题
求生产者消费者问题的代码和解释
作者:
君嘘
时间:
2015-4-9 01:49
你这问题描述太笼统了……最好是把代码发上来。然后指出看不懂的地方
作者:
吴飞飞
时间:
2015-4-9 02:34
我来帮你回复吧!回复 了就休息的
package cn.itcast_07;
//在这个类中封装了设置和获取的方法(生产者和消费者)
public class Student {
//定义的私有成员变量
private String name;
private int age;
private boolean flag;
//这个是在成员方法上加锁,其锁为this
public synchronized void set(String name, int age) {
//首先为false
if (this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 1@设置名字和年龄(先生产出来)
this.name = name;
this.age = age;
// 修改标记,叫醒下一个线程(单)
this.flag = true;
this.notify();
//有可能继续有使用权,到上面就会在if里睡觉(等待着被叫醒)
//必须由下面消费了才有可能在生产
}
//这里同理
public synchronized void get() {
if (!this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2@ 获取数据(消费)
System.out.println(this.name + "---" + this.age);
// 修改标记
this.flag = false;
this.notify();
//有可能继续有使用权,到上面就会在if里睡觉(等待着被叫醒)
//消费过了必须 先上面生产再消费
}
}
复制代码
package cn.itcast_07;
//一个生产式的多线程
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("中南海", 27);
} else {
s.set("黄鹤楼", 30);
}
x++;
}
}
}
复制代码
package cn.itcast_07;
//一个消费式的多线程
public class GetThread implements Runnable {
private Student s;
//有参构造
public GetThread(Student s) {
this.s = s;
}
//重写run方法
@Override
public void run() {
while (true) {
s.get();
}
}
}
复制代码
package cn.itcast_07;
public class StudentDemo {
public static void main(String[] args) {
//创建资源
Student s = new Student();
//一个生产一个消费的类,传递的是其共同操作的资源,这样就可以在其类中调用资 //源s的2个被封装的方法了
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
//线程类
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
//启动线程
t1.start();
t2.start();
}
}
复制代码
把Student的成员变量给私有的了。
把设置和获取的操作给封装成了功能,并加了同步。
设置或者获取的线程里面只需要调用方法。
我已经用其全部能力说清楚了!不是你不懂就是我不懂,舍其无它!!!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2