간단 한 자바 생산자 소비자 코드 예시
9140 단어 생산자 소비자
동시 프로 그래 밍 에서 생산자-소비자 모델 은 전형 적 인 문제 이다.데이터 공유 가 간단 하고 효과 적 인 수단 중 하나 입 니 다.다음은 이 모델 의 간단 한 예 이다.
코드 소개
여러 데이터 생산 자 는 데 이 터 를 버퍼 에 저장 하고 한 개 이상 의 데이터 소비 자 는 데 이 터 를 버퍼 에서 가 져 갑 니 다.
package com.two;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class EventStorage {
public int maxSize;
private List<Date> storage;
public EventStorage(){
maxSize=10;
storage=new LinkedList<Date>();
}
public synchronized void set(){
while(storage.size()>=10){
try{
wait();
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
storage.add(new Date());
System.out.println("set storage size :"+storage.size());
notifyAll();
}
public synchronized void get(){
while(storage.size()<=0){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println("get "+((LinkedList<Date>)storage).poll());
notifyAll();
}
}
package com.two;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class Consumer implements Runnable{
private EventStorage storage;
public Consumer(EventStorage storage){
this.storage=storage;
}
@Override
public void run() {
while(true){
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" storage.get.. ");
storage.get();
}
}
}
package com.two;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class Producer implements Runnable {
private EventStorage storage;
public Producer(EventStorage storage){
this.storage=storage;
}
@Override
public void run() {
while(true){
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" storage.set ");
storage.set();
}
}
}
package com.two;
/**
*
*
* @author yebing.li
* @version $Id: Main.java, v 0.1 2014 7 25 11:04:42 yebing.li Exp $
*/
public class Main {
public static void main(String[] args) {
EventStorage storage=new EventStorage();
Producer producer=new Producer(storage);
Thread thread1=new Thread(producer);
Consumer consumer=new Consumer(storage);
Thread thread2=new Thread(consumer);
thread1.start();
thread2.start();
}
}
3.다른 실현 방식 java.util.concurrent.locks.Condition
package com.two;
import java.util.Random;
public class FileMock {
private String[] content;
private int index;
public FileMock(int size,int length){
content=new String[size];
for(int i=0;i<size;i++){
StringBuilder buffer=new StringBuilder();
for(int j=0;j<length;j++){
int indice=new Random().nextInt(1000);
buffer.append(indice);
}
content[i]=buffer.toString();
}
index=0;
}
public boolean hasMoreLines(){
return index<content.length;
}
public String getLine(){
if(hasMoreLines()){
return content[index++];
}
return null;
}
}
package com.two;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Buffer {
private LinkedList<String> buffer;
private int maxSize;
private ReentrantLock lock;
private Condition lines;
private Condition space;
private boolean peedingLines;
public Buffer(int maxSize){
this.maxSize=maxSize;
buffer=new LinkedList<String>();
lock=new ReentrantLock();
lines=lock.newCondition();
space=lock.newCondition();
peedingLines=true;
}
public void insert(String line){
lock.lock();
try{
while(buffer.size()>=maxSize){
space.await();
}
buffer.offer(line);
lines.signalAll();
}catch(InterruptedException e){
e.printStackTrace();
}finally{
lock.unlock();
}
}
public String get(){
String line=null;
lock.lock();
try{
while(buffer.size()==0&&hasPeedingLines()){
lines.await();
}
if(hasPeedingLines()){
line=buffer.poll();
space.signalAll();
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
lock.unlock();
}
return line;
}
public void setPeedingLines(boolean peedingLines){
this.peedingLines=peedingLines;
}
public boolean hasPeedingLines(){
return peedingLines||buffer.size()>0;
}
}
package com.two;
public class Producerfile implements Runnable{
private FileMock mock;
private Buffer buffer;
public Producerfile(FileMock mock,Buffer buffer){
this.mock=mock;
this.buffer=buffer;
}
@Override
public void run() {
buffer.setPeedingLines(true);
while(mock.hasMoreLines()){
String line=mock.getLine();
System.out.println("Producerfile,content:"+line);
buffer.insert(line);
}
buffer.setPeedingLines(false);
}
}
package com.two;
public class ConsumerFile implements Runnable{
private Buffer buffer;
public ConsumerFile(Buffer buffer){
this.buffer=buffer;
}
@Override
public void run() {
while(buffer.hasPeedingLines()){
String line=buffer.get();
System.out.println(String.format("ConsumerFile content:%s", line));
}
}
}
package com.two;
public class FileMockMain {
public static void main(String[] args) {
FileMock mock=new FileMock(100,10);
Buffer buffer=new Buffer(20);
Producerfile producer=new Producerfile(mock,buffer);
Thread threadProducer=new Thread(producer,"Producer");
ConsumerFile consumers[]=new ConsumerFile[3];
Thread threadConsumer[]=new Thread[3];
for(int i=0;i<3;i++){
consumers[i]=new ConsumerFile(buffer);
threadConsumer[i]=new Thread(consumers[i],"consumer"+i);
}
threadProducer.start();
for(int i=0;i<3;i++){
threadConsumer[i].start();
}
}
}
코드 는 자바 7 병렬 프로 그래 밍 매 뉴 얼 에서 유래 되 었 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
복잡 한 생산자 소비자 - pthread기초 지식 사고 정리http://blog.csdn.net/aganlengzi/article/details/51416461 [1] http://www.cnblogs.com/clover-toeic/p/4029269.ht...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.