public class SortedPrint implements Runnable{
int n;
@Override
public synchronized void run(){
//有个唤醒机制
while(true){
if(n>100) return;
System.out.println(Thread.currentThread().getName()+"拿到了: "+n);
n++;
//睡觉
try {
this.notify();
this.wait(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//唤醒
if(n>100) break;
}
}
public static void main(String[] args) {
SortedPrint sortedPrint = new SortedPrint();
for (int i = 0; i < 2; i++) {
new Thread(sortedPrint).start();
}
}
}