多线程依次循环打印数据
2016-10-09 17:05
429 查看
如A,B,C,D, A,C,C,D....
方法很多,写一个可以运行的
方法很多,写一个可以运行的
package com.test.thread; import java.util.concurrent.Semaphore; /** * 三个线程,依次循环输出ABC * * Created by root on 2016/10/9. */ public class MutiThreadTest { public static void main(String[] args){ int length = 8; Semaphore[] s = new Semaphore[length]; for(int i = 0 ; i < length; i++ ){ s[i] = new Semaphore(0); } // 先放一个信号量进去 s[0].release(); PrintThread[] threads = new PrintThread[length]; for(int i = 0 ; i < length; i++ ){ threads[i] = new PrintThread((char) ('A' + i) + "" , s[i], s[(i+1) % length]); threads[i].start(); } try { Thread.currentThread().join(); } catch (InterruptedException e) { e.printStackTrace(); } } } class PrintThread extends Thread { String label = ""; Semaphore cur; Semaphore next; public PrintThread(String label, Semaphore cur, Semaphore next){ super(); this.label = label; this.cur = cur; this.next = next; } @Override public void run() { while(true){ try { cur.acquire(); System.out.println(label); } catch (InterruptedException e) { e.printStackTrace(); } finally { next.release(); } } } }
相关文章推荐
- 使用游标循环读取数据表并打印出来
- 多线程循环打印ABC10次
- 一周stackoverflow热门问题选登:如何用Python for循环实现列表中数据两两循环打印?
- 【面试库】--HashMap多线程put后get null ,get 死循环,get数据丢失(167)
- 多线程操作(循环往listbox中添加数据)
- 不用repeater datalist 打印数据 直接从后台直接打印 一个for 循环打印表格两列多行
- Java多线程循环打印ABC 10次,可能是东半球最美解决方案了
- Java多线程 循环打印ABC 10次
- java多线程轮流打印数据问题
- 【程序员面试宝典】数据结构基础二单链表循环链表的操作 建立|插入删除|打印|合并
- 【机试】华为2014校招机试:多线程循环打印十次ABC
- java 实现3个线程 依次打印ABC,并且循环10次
- java多线程循环打印A,B,C
- Java 3个线程依次打印ABC,并且循环10次
- 多线程之——实现循环打印"abc"
- 多线程按顺序依次打印ABCD---java多线程的一道经典面试题
- 迅雷笔试题 (JAVA多线程)启动三个线程,分别打印A B C,现在写一个程序 循环打印ABCABCABC
- C#中添加三个线程同时启动执行某一方法,并依次调用某方法中的循环打印输。
- ArrayList<实体类> 存入数据和循环遍历打印输出