用阻塞队列(BlockingQueue)实现读写(生产者消费者)线程

package concurrent;


import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;


/**
 * @author: kimt
 * @Version: 1.0
 * @date: 2017年11月12日 下午8:48:32
 * @modify:
 * @Description:生产者和消费者之BlockingQueue(阻塞队列)
 */
public class ProducerAndComsumer {


public static void main(String[] args) {
BlockingQueue bQueue = new LinkedBlockingQueue<>();
// 创建cached线程池
ExecutorService service = Executors.newFixedThreadPool(2);
// 创建两个任务线程实例
WriteThread producer = new WriteThread(bQueue);
ReadThread consumer = new ReadThread(bQueue);
// 执行线程
//先执行消费者线程,阻塞队列没有数据,则进入阻塞状态
service.execute(consumer);
service.execute(producer);
}


}


/**
 * 
 * 模拟生产者(写)线程
 *
 */
class WriteThread implements Runnable {
private BlockingQueue bq;
private boolean isRunning = false;


public WriteThread(BlockingQueue bq) {
this.bq = bq;
}


@Override
public void run() {
isRunning = true;
Scanner sr = null;
while (isRunning) {
System.out.println(Thread.currentThread()+"请输入数据:");
// 从键盘接收数据
sr = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
try {
//模拟生产每次写入一行数据
if (sr.hasNextLine()) {
sb.append(sr.nextLine());
}
// 将数据写入阻塞队列中
bq.put(sb.toString());
} catch (InterruptedException e) {
shutdown();
e.printStackTrace();
} 
}
}


public void shutdown() {
isRunning = false;
}


}


/**
 * 
 * 模拟消费者(读)线程
 *
 */
class ReadThread implements Runnable {
private BlockingQueue bq;
private boolean isRunning = false;


public ReadThread(BlockingQueue bq) {
this.bq = bq;
}


@Override
public void run() {
isRunning = true;
while (isRunning) {
try {
// 将数据从阻塞队列取出,并且输出到控制台
String result = bq.take();
System.out.println(Thread.currentThread()+"已取得数据:" + result);
} catch (InterruptedException e) {
shutdown();
e.printStackTrace();
}
}
}


public void shutdown() {
isRunning = false;
}


}

你可能感兴趣的:(java)