按序打印_2个线程

时间:2021-09-02 06:24:08   收藏:0   阅读:8
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();
        }
    }
}

原文:https://www.cnblogs.com/purexww/p/15209029.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!