多线程轮流打印

来源:互联网 发布:ubuntu 10.0 更新 编辑:程序博客网 时间:2024/06/12 01:23

三个线程,分别只用以打印a,b,c

用多线程实现打印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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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();    }} 


原创粉丝点击