写了一个生产者消费者模式,但好像有数据不一致的问题,先记录下:
package com.itrip.rp.openapi;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyTest {
public static void main(String[] args) {
MessageQueue queue = new MessageQueue();
for(int i = 0; i<100; i++){
Producer producer = new Producer(queue);
Thread tProducer = new Thread(producer);
tProducer.start();
}
Consumer c = new Consumer(queue);
Thread tComsumer = new Thread(c);
tComsumer.start();
}
}
class Message{
int mId;
String text;
public Message(int id) {
this.mId = id;
}
@Override
public String toString() {
return "Message [mId=" + mId + ", text=" + text + "]";
}
}
class MessageQueue{
int index = 0;
final int MAX_INDEX = 50;//消息的最大数
public List<Message> messages = new ArrayList<Message>();
//生产消息
public synchronized void push(Message m){
while(getIndex()>MAX_INDEX){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
messages.add(m);
setAddIndex();
}
/**
* 消费消息
* @return
*/
public synchronized Message pop(){
while(getIndex()==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
setSubIndex();
return messages.get(getIndex());
}
public synchronized int getIndex(){
return index;
}
public synchronized void setSubIndex(){
this.index --;
}
public synchronized void setAddIndex(){
this.index ++;
}
}
/**
* 生产消息类
* @author cheng
*
*/
class Producer implements Runnable{
MessageQueue mq = null;
Producer(MessageQueue ms){
this.mq = ms;
}
@Override
public void run() {
Message m = new Message(mq.getIndex() +1);
mq.push(m);
System.out.println("生产了id:"+m.mId+"消息");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 消费消息类
* @author cheng
*
*/
class Consumer implements Runnable{
MessageQueue mq = null;
public Consumer(MessageQueue ms) {
this.mq = ms;
}
@Override
public void run() {
//当队列里还有消息,则启动新的线程池
while (mq.getIndex() >0) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
for(int i = 0; i<5; i++){
if(mq.getIndex() >0){
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
Message m = mq.pop();
System.out.println("消费了消息:"+m);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}else{
break;
}
}
fixedThreadPool.shutdown();
while(true){
if (fixedThreadPool.isTerminated()) {
System.out.println("统一进行DB操作");
break;
}
}
}
}
}