多线程:协调顺序运行

来源:互联网 发布:ps4游戏淘宝的 认证版 编辑:程序博客网 时间:2024/05/17 22:33

要求:多个线程一起运行,每个线程的任务都是循环打印1~99的数字,轮流打印,即:如果为三个线程,打印出:1 1 1 2 2 2 3 3 3 4 4 4 5 5 5...99 99 99


public class MultiThread2 {    private static List<Integer> integers;    static final int MAX = 100;    private static final int ThreadCount = 3;    private static MyLoopList<Thread> threadList;    public static void main(String... args) throws InterruptedException {        integers = Collections.synchronizedList(new ArrayList<Integer>(ThreadCount * MAX));        threadList = new MyLoopList<>(ThreadCount);        for (int i = 0; i < ThreadCount; i++) {            threadList.put(new MyThread("t" + (i + 1)));        }        for (Thread t : threadList) {            t.start();            Thread.sleep(10);        }    }    private static void check() {        System.out.println();        System.out.println("---------------------");        for (int i = 0; i < integers.size() - ThreadCount + 1; i++) {            if (i % ThreadCount == 0) {                for (int j = 1; j < ThreadCount; j++) {                    if (!integers.get(i).equals(integers.get(i + j))) {                        System.out.println(integers.get(i) + "和" + integers.get(i + j) + "不相等");                        return;                    }                }            }        }    }    static class MyLoopList<T> extends ArrayList<T> {        private int p = 0;        int threadCount;        MyLoopList(int threadCount) {            this.threadCount = threadCount;        }        void put(T t) {            this.add(t);        }        T getNext() {            if (++p == this.size()) {                p = 0;            }            return this.get(p);        }        void interruptAll() {            for (T t : this) {                ((Thread) t).interrupt();            }        }    }    static class MyThread extends Thread {        MyThread(String name) {            this.setName(name);        }        @Override        public void run() {            for (int i = 0; i < MAX; i++) {                System.out.print(i + "\t");                integers.add(i);                runThread();            }        }    }    private static volatile AtomicInteger count = new AtomicInteger();    static void runThread() {        try {            threadList.getNext().interrupt();            //让下一个线程中断睡眠            if (count.incrementAndGet() >= ThreadCount * MAX) {//最后一次,直接检测结果是否正确                check();            } else if (count.intValue() == ThreadCount * MAX - 1) {//倒数第二次,唤醒所有,并且不睡眠                threadList.interruptAll();            } else {                Thread.sleep(10000);//让当前线程睡眠            }        } catch (InterruptedException e) {        } catch (Exception e) {            e.printStackTrace();        }    }}

原创粉丝点击