public class SortedPrintMore extends Thread{
//由于是不同的Thread n最好是共享
//无锁化
int i;
static int n;
static Lock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
public SortedPrintMore(int n) {
this.i = n;
}
//使用lock和condition
@Override
public void run() {
while(true){
if(n %3 == i){
//抢到锁了
if(n>100) return;
lock.lock();
System.out.println(Thread.currentThread().getName()+" : "+n++);
try {
condition.signalAll();
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
}
}
public static void main(String[] args) {
SortedPrintMore more1 = new SortedPrintMore(0);
SortedPrintMore more2 = new SortedPrintMore(1);
SortedPrintMore more3 = new SortedPrintMore(2);
more1.start();
more2.start();
more3.start();
}
}
按序打印_lock和condition