多线程轮流打印
2013-11-15 11:07
190 查看
三个线程,分别只用以打印a,b,c
用多线程实现打印abc重复10次
我想了一个比较丑的方法,就是一个命令者,用以发布命令,这次要打印那个字符,三个打印者就分别检查这个指令是否是发给自己的
用多线程实现打印abc重复10次
我想了一个比较丑的方法,就是一个命令者,用以发布命令,这次要打印那个字符,三个打印者就分别检查这个指令是否是发给自己的
class ShId { private int value; public ShId(int id) { value = id; } public void set(int i) { value = i; } public boolean isEqual(Integer i) { return i.intValue() == value; } @Override public boolean equals(Object o) { if (this == o) return true; return ((ShId)o).value == value; } } class Work implements Runnable { private String name; private Integer id; private ShId shId; public Work(String name, Integer id, ShId shId) { this.name = name; this.id = id; this.shId = shId; } @Override public void run() { try { while (true) { synchronized (shId) { while(!shId.isEqual(id)) { shId.wait(); } System.out.print(name); shId.set(-1); shId.notifyAll(); if (name.equals("c")) System.out.println(); } } } catch(InterruptedException e) { e.printStackTrace(); } } } class Produce implements Runnable { private int count; private ShId shId; public Produce (int count, ShId shId) { this.count = count; this.shId = shId; } @Override public void run() { try { while (count >0) { for (int i = 0; i < 3; ++i) { synchronized (shId) { while (!shId.isEqual(new Integer(-1))) { shId.wait(); } shId.set(i); shId.notifyAll(); } } --count; } } catch (InterruptedException e) { } } } public class testt { public static void main(String[] args) { ShId shId = new ShId(-1); Work w1 = new Work("a",0, shId); Work w2 = new Work("b",1, shId); Work w3 = new Work("c",2, shId); Produce p = new Produce(10, shId); new Thread(w1, "work1").start(); new Thread(w2, "work2").start(); new Thread(w3, "work3").start(); new Thread(p, "produce").start(); } }
相关文章推荐
- java多线程轮流打印数据问题
- 面试题多线程轮流打印ABC初试
- JAVA 多线程轮流打印ABC
- 多线程--同时轮流打印ABC
- 三个线程轮流执行顺序打印ABC(二):使用Lock+Condition实现
- 题目:有三个线程分别打印A、B、C,请用多线程编程实现,在屏幕打印10次ABC
- 多线程交替打印ABC的多种实现方法
- JAVA程序设计(18.1)----- 1多线程轮流打印 线程调度 线程池 synchronized wait notify 内部类
- JAVA多线程打印ABC
- java wait notify notifyAll and 多线程顺序打印ABCD
- java 线程上机题 循环唤醒 三个线程轮流打印 顺序 A线程->B线程->C线程
- 多线程循环打印
- log4j2 异步多线程打印日志
- 练习:利用多线程 按照顺序将 ABC 打印十遍 ,体会 lock 和 condition 的用法
- python 多线程服务器验证,实现断开重连,信号量解决主线程Ctrl+C不退出问题,多线程打印错行问题
- 多线程和akka实现两个数组交替打印
- valgrind 打印程序调用树+进行多线程性能分析
- N个线程轮流打印数字问题
- 多线程打印日志面试题
- JAVA 多线程开篇 -从按顺序打印ABC开始