多个线程按顺序循环打印线程独有的字符串
来源:互联网 发布:nginx 静态页面 编辑:程序博客网 时间:2024/06/05 15:55
package multithreading.analysis;import java.util.LinkedList;import java.util.Queue;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;import org.junit.Test;/** * n个线程,每个线程打印的数字不一样,必须按顺序打印 * @author mxipjs * */public class AQSTest { private static ReentrantLock rtl = new ReentrantLock(); private static Queue<Condition> queue = new LinkedList<Condition>(); @Test public void test() throws InterruptedException{ ExecutorService exec = Executors.newCachedThreadPool(); for(int i=0;i<20;i++){ Condition con = rtl.newCondition(); queue.offer(con); exec.execute(new PrintC(con,i+"")); } TimeUnit.SECONDS.sleep(1); rtl.lock(); try { PrintC.signal(queue); //开始通知第一个打印线程 }finally { rtl.unlock(); } exec.shutdown(); while(Thread.activeCount()>2){ Thread.yield(); } System.out.println("over"); } static class PrintC implements Runnable { private String printStr; private static ThreadLocal<Integer> count = new ThreadLocal<Integer>(){ protected Integer initialValue() { return new Integer(3); }; }; private Condition con; public PrintC(Condition con,String str) { this.con = con; this.printStr = str; } @Override public void run() { while(count.get()>0){ rtl.lock(); try { con.await(); System.out.println(printStr); signal(queue); count.set(count.get()-1); } catch (InterruptedException e) { e.printStackTrace(); } finally{ rtl.unlock(); } } } public static void signal(Queue<Condition> queue){ Condition tempCondition = queue.poll(); tempCondition.signal(); queue.offer(tempCondition); } }}
阅读全文
0 0
- 多个线程按顺序循环打印线程独有的字符串
- 三个线程循环的按顺序打印
- 顺序打印多个线程ID
- 按顺序打印线程
- 3个线程顺序打印ABC10次
- 3个线程循环打印ABC
- 多线程(至少三个线程)分别打印A、B、C,要求按ABC的顺序循环打印10次。
- 创建线程打印字符串_2个线程打印
- 编写程序,循环接收用户从键盘输入多个字符串,直到输入“end”时循环结束,并将所有已输入的字符串按字典顺序倒序打印。
- 编写程序,循环接收用户从键盘输入多个字符串,直到输入“end”时循环结束,并将所有已输入的字符串按字典顺序倒序打印。
- 编写程序,循环接收用户从键盘输入多个字符串,直到输入“ end”时循环结束,并将所有 已输入的字符串按字典顺序倒序打印。
- [笔试]线程共享和独有的资源
- 多线程编程(二)——面试题,每个线程只打印一种字符,多个线程协同顺序打印n次字符串(求大神的其他实现方案)
- 3个线程每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次
- 多线程题 3个线程各打印一种字母,按顺序打印若干次ABC 的2种实现
- 多个线程按顺序输出
- 线程顺序打印ABC
- java 线程上机题 循环唤醒 三个线程轮流打印 顺序 A线程->B线程->C线程
- 设计模式-解释器模式
- SPA开发第一天(vue-cli)
- matlab调用python代码
- java.lang.IllegalArgumentException: Wrong FS://expected: file:///
- TensorFlow 整体架构 / 第1节:TensorFlow 概要
- 多个线程按顺序循环打印线程独有的字符串
- 详解MySql的慢查询分析及开启慢查询日志
- 用户账户的创建和管理
- Linux-内核通信之netlink机制-详解
- Linux网络编程(三)多路IO转接服务器
- fatal: cannot resume: .git/rebase-apply/final-commit does not exist.
- ArrayList和Vector的扩容机制
- Spring事务管理
- mysql 不是主键自增长