标题: 给大家分享一个线程的设计案例--生产者和消费者 [打印本页] 作者: 清风小雨 时间: 2016-10-19 19:26 标题: 给大家分享一个线程的设计案例--生产者和消费者 生产者不断地生产信息,消费者不断地取走信息。生产者产生了信息,消费者才能取走。
class Info{
private String name;
private String job;
private boolean flag=false; // 定义生产标记位
public void setName(String name) {
this.name = name;
}
public void setJob(String job) {
this.job = job;
}
public String getName() {
return name;
}
public String getJob() {
return job;
}
public synchronized void set(String name,String job){
if(!flag){
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
this.setName(name);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.setJob(job);
flag=false;
super.notify();
}
}
public synchronized void get(){
if(flag){
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName()+"-->"+this.getJob());
flag = true;
super.notify();
}
}
}
class Product implements Runnable{
private Info in = null;
public Product(Info in){
this.in = in;
}
@Override
public void run() {
// TODO Auto-generated method stub
boolean flag=false; // 定义标记位
for(int i=0;i<50;i++){
if(flag){
this.in.set("smith","student");
flag = false;
}else{
this.in.set("tom","teacher");
flag = true;
}
}
}
}
class Consumer implements Runnable{
private Info out = null;
public Consumer(Info out){
this.out = out;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<50;i++){
this.out.get();
}
}
}
public class TreadDemo4 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Info info = new Info();
Product p = new Product(info);
Consumer c = new Consumer(info);
new Thread(p).start();
new Thread(c).start();
}