在網上看到一道類似生產者和消費者問題的筆試題,大致內容如下:
有3個線程,要求分別打印出字母A、B、C,並且按順序打印10次"ABCABC......ABC"。
網上有人給出了一些答案,不過都有些小bug,自己修改了一下,運行成功,代碼如下:
public class Test {
public static void main(String[] s){
Status status = new Status();
MyThread t1 = new MyThread("A",status);
MyThread t2 = new MyThread("B",status);
MyThread t3 = new MyThread("C",status);
t1.start();
t2.start();
t3.start();
}
}
class MyThread extends Thread{
String id;
Status status;
int myStatus;
public MyThread(String id,Status status){
this.id=id;
this.status=status;
myStatus=id.charAt(0)-'A';
}
public void run(){
for(int i=0;i <10;i++){
synchronized (status){
while(status.getStatus() != myStatus){
try{
status.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.print(id);
status.setStatus(myStatus + 1);
status.notifyAll();
}
}
}
}
class Status {
public int status=0;
public int getStatus(){
return status%3;
}
public void setStatus(int status){
this.status=status;
}
}
希望對大家有點用處!