按序打印_2个线程

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();
        }
    }
}
posted @ 2021-08-31 10:10  常熟阿诺  阅读(13)  评论(0编辑  收藏  举报