您的位置:首页 > 其它

多线程轮流打印

2013-11-15 11:07 190 查看
三个线程,分别只用以打印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;
}

@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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: