package test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] args) {
Test t = new Test();
ExecutorService es = Executors.newCachedThreadPool();
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
Lock lock = t.new Lock(list);
lock.list.forEach(e -> es.execute(t.new MyPrint(lock, e, 100)));
es.shutdown();
}
class Lock {
List<String> list;
String str;
Lock(List<String> list) {
this.list = list;
this.str = list.get(0);
}
}
class MyPrint implements Runnable {
String str;
Lock lock;
int loopNum;
final int num;
MyPrint(Lock lock, String str, int loopNum) {
this.lock = lock;
this.str = str;
this.loopNum = loopNum;
num = lock.list.indexOf(str);
}
@Override
public void () {
synchronized (lock) {
while (true) {
if (lock.str.equals(str)) {
System.out.println(str);
lock.str = (num + 1 == lock.list.size() ? lock.list.get(0) : lock.list.get(num + 1));
lock.notifyAll();
if (loopNum-- == 0)
break;
} else {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}
近期评论