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

java多线程之 生产者和消费者 线程间通信 等待与唤醒机制

2016-08-03 22:02 851 查看
生产者和消费者 线程间通信  等待与唤醒机制
  必须生产者生产,消费者才能消费

  生产者生产一个 ,消费者才能消费,否则等待,等待消费者消费一个后去唤醒

  消费者消费一个,生产者才能生产,否则等待,等待生产者生产一个后去唤醒

  Oject类中3个方法:

  1.notify() 唤醒单个线程

  2.notifyAll()唤醒所有线程

  3.wait() 等待线程

 注意 同步唤醒机制在同步锁内进行,先判断等待wait() ,然后执行多线程共同操作的内容,最后唤醒notify()

[b]1.测试类
[/b]

package ProductorAndConsumer;
/**
* 测试类
* @author feige
*/
public class StudentDemo {

public static void main(String[] args) {
Student s=new Student();
StudentProductor sp=new StudentProductor(s);
StudentConsumer sc=new StudentConsumer(s);
Thread spt=new Thread(sp);
Thread sct=new Thread(sc);
spt.start();
sct.start();
}
}
2.student类

package ProductorAndConsumer;

/**
* 学生类
* @author feige
*/
public class Student {
private String name;
private int age;
boolean flag;

public synchronized void set(String name, int age) {
while (this.flag) {// 如果有货,就等待消费者消费
try {
this.wait();// 先判断等待,等唤醒后从这里开始
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
this.age = age;

System.out.println("生产者:name="+this.name+",年龄="+this.age);

this.flag = true;
this.notify();// 生产完后,解锁,去通知消费者,但此时消费者不能保证立马获得cpu执行权限,只能去竞争资源
}

public synchronized void get() {
while (!this.flag) {// 如果没货,就等待生产者生产
try {
this.wait();// 先判断等待,等唤醒后从这里开始
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者:name=" + this.name + ",年龄=" + this.age);
this.flag = false;
this.notify();// 消费完一个后,就通知生产者,同样不能保证生产者立马获得cpu执行权限,只能去竞争资源
}
}

3.StudentProductor类 生产者


package ProductorAndConsumer;
/**
* 生产者
* @author feige
*/
public class StudentProductor implements Runnable {
private Student s;
private int x=1;

public StudentProductor(Student s) {
this.s=s;
}
@Override
public void run() {
while(true){
if(x%2==0){
s.set("阿飞",25);
}else{
s.set("阿瑞",24);
}
x++;
}
}
}
4.[b] StudentConsumer类  消费者[/b]

package ProductorAndConsumer;
/**
* 消费者
* @author feige
*/
public class StudentConsumer implements Runnable{
private Student s;

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

@Override
public void run() {
while(true){
s.get();
}
}
}
运行结果可以看到 生产者和消费者交替进行




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐