1. Car程序
class Car{
Logger logger = LoggerFactory.getLogger(Car.class);
public void waxOn(){
logger.info("wax On");
}
public void waxOff(){
logger.info("wax Off");
}
}
2. WaxOn任务
class WaxOn implements Runnable{
private Car car;
public WaxOn() {
}
public WaxOn(Car car){
this.car = car;
}
@Override
public void run() {
car.waxOn();
}
}
3. WaxOff任务
class WaxOff implements Runnable {
private Car car;
public WaxOff(){
}
public WaxOff(Car car) {
this.car = car;
}
@Override
public void run() {
car.waxOff();
}
}
4. WaxRunner消费者任务
class WaxRunner implements Runnable {
private BlockingQueue queue;
public WaxRunner(BlockingQueue queue){
this.queue = queue;
}
@Override
public void run() {
while (!queue.isEmpty()) {
Object remove = queue.remove();
if(remove.getClass().isInstance(new WaxOn())){
((WaxOn)remove).run();
}else{
((WaxOff)remove).run();
}
}
}
}
5. 测试类
public class TestWaxBlockingQueue {
public static void main(String[] args){
Car car = new Car();
//执行三次waxOn waxOff
BlockingQueue queue = new LinkedBlockingDeque();
for (int i = 1; i <= 3; i++) {
WaxOn waxOnTask = new WaxOn(car);
queue.add(waxOnTask);
WaxOff waxOffTask = new WaxOff(car);
queue.add(waxOffTask);
}
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new WaxRunner(queue));
try {
TimeUnit.MILLISECONDS.sleep(3000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(0);
}
}
运行结果:
类图:
对于WaxOnWaxOff程序的实现,一种是使用wait和notifyAll来实现,另一种是使用同步队列来实现。
总结来说:
1. wait()和notifyAll()方法以一种非常低级的方式解决了任务互操作问题,即每次交互时都握手。而同步队列是更高的抽象级别。
2. BlockingQueue将多个任务的执行串行化,而且均在消费者线程上执行多个任务
3. 在使用BlockingQueue时没有使用任何显示的同步(如Lock对象或Synchronized关键字),因为同步由队列(其内部是同步的)和系统的设计隐式地管理了。因为队列的阻塞,使得处理过程将被自动地挂起和恢复。你可以看到由BlockingQueue产生的简化十分明显。在使用显式的wait()和notify()时存在的类和类之间的耦合被消除了,因为每个任务类都只和它的BlockingQueue通信。
4. 如何像消费者线程中传递信息呢?在这里是将装载任务的BlockingQueue通过构造函数,设置任务类的字段实现的