java程序模拟生产者与消费者

模拟流程实现

1.创建消息类,供生产者与消费者使用

2.创建消费者,负责生产消息

3.创建消费者,负责消费消息

所需知识:多线程创建、wait、notify与notifyAll使用,里面有不懂的内容欢迎留言

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 测试类
 * @author TT
 *
 */
public class Test87 {
public static void main(String[] args) {
Message m = new Message();
P p = new P(m);
C c = new C(m);
new Thread(p).start();
new Thread(c).start();
}
}


/**
 * 消息类
 * @author TT
 *
 */
class Message {
public final static int MAXQUENE = 5;
private List<String> msgs = new ArrayList<String>();

public List<String> getMsgs() {
return msgs;
}

public void setMsgs(List<String> msgs) {
this.msgs = msgs;
}
}


/**
 * 生产者
 * @author TT
 *
 */
class P implements Runnable {

private Message m;

P() {}

P(Message m) {
this.m = m;
}


public Message getM() {
return m;
}


public void setM(Message m) {
this.m = m;
}


@Override
public void run() {
while(true) {
add();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private void add() {

synchronized(m) {
while(m.getMsgs().size() == Message.MAXQUENE) {
try {
m.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("添加成功");
m.getMsgs().add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
m.notifyAll();
}

}
}


/**
 * 消费者
 * @author TT
 *
 */
class C implements Runnable {

private Message m;

C() {}

C(Message m) {
this.m = m;
}


public Message getM() {
return m;
}


public void setM(Message m) {
this.m = m;
}


@Override
public void run() {
while(true) {
sub();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private void sub() {

synchronized(m) {
while(m.getMsgs().size() == 0) {
try {
m.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String msg = m.getMsgs().remove(0);
System.out.println("消费了消息" + msg);
m.notifyAll();
}
}
}




猜你喜欢

转载自blog.csdn.net/zhaosx1234567/article/details/80353558