之前面试的时候遇到过这么一道题,3个线程同时启动,要求按照 one, two, three的顺序打印,在这里记录一下如何实现,方法可能有点low
class test
{
private static String[] ss = {"one", "two", "three"};
public static void main (String[] args){
Runnable r = new Runnable() {
int flag = 0;
@Override
public synchronized void run() {
while (!Thread.currentThread().getName().equals(flag + "")) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(ss[flag]);
flag++;
notifyAll();
}
};
for (int i = 0; i < ss.length; i++) {
new Thread(r, i + "").start();
}
}
}