多线程:协调顺序运行
来源:互联网 发布: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(); } }}
阅读全文
1 0
- 多线程:协调顺序运行
- Java多线程协调控制之wait¬ifyAll
- android多线程并发协调semaphore机制
- Python多线程编程,线程之间的协调
- Java多线程(四)- 协调同步线程
- 使用并发与协调运行时
- 进程协调运行的两种方式
- 多线程间的协调实战——多线程轮流处理
- 运行顺序
- 再谈多线程信号量同步(协调)方法的本质
- Java多线程如何才能协调好生产和消费的关系
- wait与notify实现多线程的协调通信
- 面试题12解析-多线程之间的协调示例
- Python中使用threading.Event协调线程的运行
- Java多线程顺序执行
- 多线程执行顺序
- 多线程顺序打印ABC
- 多线程的顺序锁
- c语言基础(四)
- Visual Studio中Radio Button组绑定变量方法(DDX_Radio方法)
- 【AR技术点】(一)如何通过捕捉特征图像来建立起三维空间
- 整合ssm思路
- HDOJ2103 Family planning
- 多线程:协调顺序运行
- 刷新输出缓冲区操作flush & ends & endl
- 使用main函数的参数,实现一个整数计算器.
- uva10820(欧拉函数)
- 延迟
- [leetcode] 547. Friend Circles
- C++标准库中string类的介绍
- Python运维自动化开发之Paramiko模块
- VM下Linux的安装步骤(超详细)