黑马程序员技术交流社区
标题:
生产者与消费者
[打印本页]
作者:
王峰峰
时间:
2014-4-3 22:01
标题:
生产者与消费者
题目:
生产者与消费者,生产者要求生产两种信息(
1
、王峰峰
– JAVA
学生
2
、
wff – www.wff.com
)
,
生产与消费规定是:要求生产者交替生产这两种信息,生产者生一种等待消费者取走后再生产另一种信息,生产
50
次。
以下是要操作的信息类:
public class Info {
private String name = "王峰峰" ;
private String content = "JAVA 学生" ;
private boolean flag = false ; //定义标记位
public synchronized void set(String name, String content) { //设置信息
if(!flag) { //表示已经有值,不能在生产
try {
super.wait() ;
}catch(InterruptedException e){
e.printStackTrace() ;
}
}
this.setName(name) ;
try {
Thread.sleep(300) ;
}
catch (Exception e){
e.printStackTrace() ;
}
this.setContent(content) ;
flag = false ; //改变标记位,表示可以取值了
super.notifyAll() ;
}
public synchronized void get() { //打印信息
if(flag) { //表示没有值,只能生产
try {
super.wait() ;
}
catch(InterruptedException e){
e.printStackTrace() ;
}
}
System.out.println(this.getName() + " --> " +
this.getContent()) ;
flag = true ;
super.notifyAll() ;
}
public void setName(String name) {
this.name = name ;
}
public void setContent(String content) {
this.content = content ;
}
public String getName() {
return this.name ;
}
public String getContent() {
return this.content ;
}
}
复制代码
以下是生产者类:
public class Producer implements Runnable {
private Info info = null ; //用来保存Info的引用
public Producer(Info info) {
this.info = info ;
}
public void run() {
//定义标记位,如果为true生产一种信息,\
//为false生产另一种信息
boolean flag = false ;
for(int i=0; i<50; i++) {
if(flag) {
info.set("王峰峰","Java 学生") ;
flag = false ;
}else {
info.set("wff","www.wff.com") ;
flag = true;
}
}
}
}
复制代码
以下是消费者类:
//消费者
public class Consumer implements Runnable{
private Info info ;
public Consumer(Info info) {
this.info = info ;
}
public void run() {
for(int i=0; i<50; i++) {
info.get() ;
}
}
}
复制代码
以下是测试类:
public class ThreadTest {
public static void main(String[] args) {
Info info = new Info() ; //信息类
Producer pro = new Producer(info) ; //生产者
Consumer con = new Consumer(info) ; //消费者
new Thread(pro).start() ;
new Thread(con).start() ;
}
}
复制代码
作者:
2528870651
时间:
2014-4-6 10:24
嗯 不错啊
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2