package test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("fn");
new Myprin(list, 50).run();
}
}
class Myprin {
private final Lock lock = new ReentrantLock();
int times;
List<MyMap> maps = new ArrayList<MyMap>();
MyMap map;
String printStr;
int n = 1;
Myprin(List<String> list, int times) {
for (String str : list) {
map = new MyMap(str, lock.newCondition());
maps.add(map);
}
printStr = list.get(0);
this.times = times;
}
void () {
for (int i = 0; i < maps.size() - 1; i++) {
new Thread(
new Print(maps.get(i).condition, maps.get(i + 1).condition, maps.get(i).str, maps.get(i + 1).str))
.start();
}
new Thread(new Print(maps.get(maps.size() - 1).condition, maps.get(0).condition, maps.get(maps.size() - 1).str,
maps.get(0).str)).start();
}
class MyMap {
String str;
Condition condition;
MyMap(String str, Condition condition) {
this.str = str;
this.condition = condition;
}
}
class Print implements Runnable {
Condition thisCondition;
Condition nextCondition;
String thisStr;
String nestStr;
Print(Condition thisCondition, Condition nextCondition, String thisStr, String nestStr) {
this.thisCondition = thisCondition;
this.nextCondition = nextCondition;
this.thisStr = thisStr;
this.nestStr = nestStr;
// System.out.println("thisStr:" + thisStr + ",nestStr:" + nestStr);
}
@Override
public void () {
while (times > 0) {
if (printStr.equals(thisStr)) {
lock.lock();
try {
if (thisStr.equals(maps.get(0).str)) {
System.out.println("第:" + n++ + "次打印");
} else if (thisStr.equals(maps.get(maps.size() - 1).str)) {
times--;
}
System.out.print(thisStr);
printStr = nestStr;
if (times == 0) {
for (MyMap map : maps) {
map.condition.signalAll();
}
break;
}
nextCondition.signalAll();
thisCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
}
}
近期评论