package org.westos.生產者消費者模式;
/*
* 消費者與生產者模式:
* 消費者:輸出數據
* 生產者:產生數據
* 這種模式中出了生產者消費者線程,我們還需要設置資源類,即包含數據的對象,還有測試類
* */
/**
* 這是一個測試類,它將會輸出成片的資源類對象的信息,而不是像SetStudent代碼那樣相互交叉輸出,這是因爲沒有等待喚醒機制
* 在加入Java等待喚醒機制後:
* 消費者:輸出數據,當內存中有對象時,纔會輸出數據,否則處於等待中,向生產者發送信號,要求產生數據
* 生產者:產生數據,當內存中沒有對象時,纔會產生對象並設置數據,否則處於等待中,向消費者發送信號,要求輸出數據
* 這就需要我們在Get/SetStudent線程中對資源類對象進行判斷
* */
/**
* wait()與sleep()的區別
* wait()線程等待,停下當前線程去執行其他線程,會釋放鎖對象
* sleep()線程睡眠,理解爲在線程中加入的一個延時函數,不會釋放所對象
* */
public class Text {
public static void main(String[] args) {
Student s = new Student();
SetStudent ss = new SetStudent(s);
GetStudent gs = new GetStudent(s);
Thread t1 = new Thread(ss,"生產者線程");
Thread t2 = new Thread(gs,"消費者線程");
t1.start();
t2.start();
}
}
package org.westos.生產者消費者模式;
/**
* 這是一個資源類;
* 用於包含了學生的姓名,年齡數據
* */
public class Student {
private String name;
private int age;
//用於等待喚醒機制的判斷
public boolean flag;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
package org.westos.生產者消費者模式;
/**
* 這是一個生產者,用於用於設置資源類對象的數據
* */
public class SetStudent implements Runnable {
//將生產者與資源類關聯起來
private Student s;
public SetStudent(Student s) {
this.s =s;
}
private int i = 0;//一個用於判斷的變量
@Override
public void run() {
while(true) {
synchronized (s) {
if(s.flag) {
try {
s.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i%2==0) {
s.setName("張三");
s.setAge(12);
}else {
s.setName("李四");
s.setAge(13);
}
i++;
s.flag = true;
s.notify();
}
}
}
}
package org.westos.生產者消費者模式;
/**
* 這是一個消費者
* */
public class GetStudent implements Runnable{
private Student s;
public GetStudent(Student s) {
this.s = s;
}
@Override
public void run() {
while(true) {
synchronized (s) {
if(!s.flag) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s);
s.flag = false;
s.notify();
}
}
}
}