public class MainThread {
public static ReentrantLock lock=new ReentrantLock();
public static void main(String[] args) throws Exception {
ArrayList<Thread> list=new ArrayList<>();
Scanner in =new Scanner(System.in);
int n=in.nextInt();
ArrayList<Condition> conlist=new ArrayList<>();
boolean []flag=new boolean[n];
for(int i=0;i<n;i++)
{
conlist.add(lock.newCondition());
}
for(int i=0;i<n;i++) {
final int j=i;
list.add( new Thread(new Runnable() {
@Override
public void run() {
try {
lock.lock();
int c=j;
if(c>0){
//while条件限制
while(!flag[c]){
conlist.get(j).await();
}
}
System.out.println(c+1);
if(c+1<n)
{
flag[c+1]=true;//一种标识,类似生产消费模型的数量标识
conlist.get(c+1).signal();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}));
}
for(int i=0;i<n;i++)
{
list.get(i).start();
}
}
}
输出:
9
1
2
3
4
5
6
7
8
9
当然也可以使用countdownLatch实现,同步