一个按顺序输出的多线程调度示例
啥叫StepByStep就是一步一步来,让子弹飞中的那句经典台词就是“钱得一点一点赚,步子得一步一步迈,不然咔容易扯着蛋”,说的就是做事情按照一定的规律和顺序来。n个线程,各自执行一段业务逻辑,应业务需求现在需要将这些业务逻辑进行step and step 的完成,带有一定顺序,好比A 线程 输出A, B线程输出B,C线程输出C....现在的要求就是整个业务处理流程就是A-->B-->C 的步骤,晚上模拟了一把。代码见下面:package com.blackbeans.example;import java.util.concurrent.LinkedBlockingQueue;/** ** 一个按顺序输出的多线程调度示例 * @author blackbeans.zc@gmail.com * */public class SequentialOutputDemo { public static void main(String[] args) {/*** 使用队列来构造、保证业务调用的顺序,* 想法是所有线程从这个队列头部取出令牌,* 如果这个令牌不属于自己线程管辖范围,则不予理睬* 如果这个令牌属于自己线程管辖的范围,那么* 1.执行业务操作* 2.取出对猎头部令牌并将该令牌插入队尾,来构成环形顺序,这一步一定要保证原子*/ final LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(8); queue.offer(0); queue.offer(1); queue.offer(2);//控制调用次数 final int count = 1000; new Thread(new Runnable() {@Overridepublic void run() {int i=0;while(i<count){/** * 检测队首的元素是否为当前线程需要 */int index = queue.peek();if(index == 0){System.out.print("A\t");/** * 取出队首的令牌并保证原子性插入队尾 */pollAndOffer(queue);i++;}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {int i=0;while(i<count){int index = queue.peek();if(index == 1){System.out.print("B\t");pollAndOffer(queue);i++;}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {int i=0;while(i<count){int index = queue.peek();if(index == 2){System.out.print("C\n");pollAndOffer(queue);i++;}}}}).start(); }private static void pollAndOffer(LinkedBlockingQueue<Integer> queue){ synchronized (queue) { queue.offer(queue.poll()); } }}
页:
[1]