java多线程中怎么依次循环输出字母A,B,C

还是我自己来吧,是这样的。。。。

public class ABCThread implements Runnable{
String id;
static String stu="A";
public ABCThread(String id){
this.id=id;
}
@Override

public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (stu) {
System.out.println(Thread.currentThread().getName()+"="+stu);
if(stu.equals("A")){
stu="B";
}
else if(stu.equals("B")){
stu="C";
}

else if(stu.equals("C")){
stu="A";
}

}

}
}
public static void main(String[] args) {
new Thread(new ABCThread("A")).start();
new Thread(new ABCThread("B")).start();
new Thread(new ABCThread("C")).start();
}

}

不知道你是不是这个意思。
有多个线程,每一个要输出的时间不固定。但你想要输入出,是个有序的。即轮到那个线程,取值都是有序的。

如果是这样,你可以将A,B,C这样的值放到一个类中。

public class Values {

private char[] chars = { 'A', 'B', 'C' };
private int index = 0;
public static Values _instance = null;

private Values() {

}

public static Values getInstance() {
if (_instance == null) {
_instance = new Values();
}
return _instance;
}

public char getValue() {
if (index >= chars.length) {
return ' ';
}
return chars[index++];
}
}

Values.getInstance().getValue()

这样用单例模式,可以顺次取得。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-22
休眠,用休眠时间控制,多线程不稳定,除了休眠,我想应该没其他方法了.
相似回答