日期:2014-05-20 浏览次数:20776 次
package design;
public class Producer implements Runnable {
Buffer buffer;
Producer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.produce(new Policy(i+"","test"+i));
}
}
}
package design;
public class Consumer implements Runnable{
Buffer buffer;
Consumer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
if (buffer.bufferList.size() > 0) {
buffer.consume(buffer.bufferList.get(0));
}
}
}
package design;
import java.util.ArrayList;
import java.util.List;
public class Buffer {
public static List<Policy> bufferList = new ArrayList<Policy>();
public synchronized void produce(Policy policy) {
bufferList.add(policy);
System.out.println("produce" + bufferList.size());
}
public synchronized void consume(Policy policy) {
if (bufferList.size() > 0) {
bufferList.remove(policy);
System.out.println("consume" + bufferList.size());
}
}
}
package design;
public class Policy {
Policy(String policy_id,String policy_name) {
this.policy_id = policy_id;
this.policy_name = policy_name;
}
private String policy_id;
private String policy_name;
public String getPolicy_id() {
return policy_id;
}
public void setPolicy_id(String policy_id) {
this.policy_id = policy_id;
}
public String getPolicy_name() {
return policy_name;
}
public void setPolicy_name(String policy_name) {
this.policy_name = policy_name;
}
public String toString() {
return "("+policy_id+","+policy_name+")";
}
}
package design;
import java.util.ArrayList;
import java.util.List;
/**
* 房顶上
* @author zhan.shi
*
*/
public class test {
public static void main(String[] args) {
Buffer buffer = new Buffer();
Thread p1 = new Thread(new Producer(buffer));
Thread c1 = new Thread(new Consumer(buffer));
Thread c2 = new Thread(new Consumer(buffer));
p1.start();
c1.start();
c2.start();
try {
p1.join();
c1.join();
c2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0;i < buffer.bufferList.size();i++){
System.out.println(buffer.bufferList.get(i).toString());
}
}
}