定义共享数据封装
package com.xqi.p_c;
/**
* 请求数据封装(以不变模式定义)
*
* @author mike <br>
* 2015年7月24日
*/
public final class PCData {
private final int intData;
public PCData(int d) {
intData = d;
}
public PCData(String d) {
intData = Integer.valueOf(d);
}
public int getData(){
return this.intData;
}
@Override
public String toString() {
return "data:" + intData;
}
}
2. 定义生产者
package com.xqi.p_c;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 定义生产者
*
* @author mike <br>
* 2015年7月24日
*/
public class Produer implements Runnable {
/* 用volatile来修饰的变量,表示随时都可能被其他的线程来改变,并使其他的线程直接访问此变量,而不保存其他的备份! */
private volatile boolean isRunning = true;
/* 定义内存缓冲区,来存放生产者提交的请求与数据, PCData就是数据的封装 */
private BlockingQueue<PCData> queue;
/* 总数,原子操作 ,AtomicInteger提供线程安全的加减操作接口 */
private static AtomicInteger count = new AtomicInteger();
/* 休眠时间 */
private static final int SLEEPTIME = 1000;
/**
* 构造方法,注入缓冲队列
*
* @param queue
*/
public Produer(BlockingQueue<PCData> queue) {
this.queue = queue;
}
public void run() {
PCData data = null;
Random r = new Random();
System.out.println("start produer id = " + Thread.currentThread().getId());
try {
while (isRunning) {
Thread.sleep(r.nextInt(SLEEPTIME)); // 使用随机产生时间差(消费者中一样)
data = new PCData(count.incrementAndGet());// incrementAndGet表示+1
System.out.println(data + " is put into queue!");
if (!queue.offer(data, 2, TimeUnit.SECONDS)) {// 设定等待的时间为2秒,如果在指定的时间内,还不能往队列中加入,则返回失败。
System.err.println("failed to put data : " + data);
}
}
} catch (InterruptedException e) {// 如果发生了异常就中断这个线程
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
//
public void stop() {
isRunning = false;
}
}
3. 定义消费者
package com.xqi.p_c;
import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
/**
* 消费者
*
* @author mike <br>
* 2015年7月24日
*/
public class Consumer implements Runnable {
private BlockingQueue<PCData> queue;
private static final int SLEEPTIME = 1000;
public Consumer(BlockingQueue<PCData> queue) {
this.queue = queue;
}
public void run() {
System.out.println("start consumer id = " + Thread.currentThread().getId());
Random r = new Random();
try {
while (true) {
PCData data = queue.take();// 取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止
if (null != data) {
int re = data.getData() * data.getData();
System.out.println(MessageFormat.format("{0}*{1}={2}", data.getData(), data.getData(), re));
Thread.sleep(r.nextInt(SLEEPTIME));
}
}
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
4. 测试主类
package com.xqi.p_c;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
/**
* 测试主类
*
* @author mike <br>
* 2015年7月24日
*/
public class PCTest {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<PCData> queue = new LinkedBlockingQueue<PCData>(10);
// 创建生产者
Produer p1 = new Produer(queue);
Produer p2 = new Produer(queue);
Produer p3 = new Produer(queue);
// 创建消费者
Consumer c1 = new Consumer(queue);
Consumer c2 = new Consumer(queue);
Consumer c3 = new Consumer(queue);
// 创建线程池,newCachedThreadPool 定义了短期可重用的线程池
ExecutorService service = Executors.newCachedThreadPool();
// 运行生产者和消费者
service.execute(p1);
service.execute(p2);
service.execute(p3);
service.execute(c1);
service.execute(c2);
service.execute(c3);
Thread.sleep(10 * 1000);
// 终止线程中的while
p1.stop();
p2.stop();
p3.stop();
Thread.sleep(3000);
// shutdown() This method does not wait for previously submitted tasks to complete execution.
// shutdown() 这个方法不会等待任务执行完成。(有说:不再接受新的任务,如果有等待的任务,就执行完成)
service.shutdown();
// Attempts to stop all actively executing tasks, halts the
// processing of waiting tasks, and returns a list of the tasks
// that were awaiting execution. These tasks are drained (removed)
// from the task queue upon return from this method.
// 立即变为shutdown状态,如果有正在执行的任务,尝试停止,并返回未完成的任务列表,然后移除
// List<Runnable> taskList = service.shutdownNow();
System.out.println("程序结束!");
}
}
Ps:感觉shutdown了以后,线程还是没有终止,也进行不了操作??????不知道为什么!