首页 > 编程语言 > 详细

按序打印_2个线程

时间:2021-09-02 06:24:08      阅读:8      评论:0      收藏:0      [点我收藏+]
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();
        }
    }
}

按序打印_2个线程

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!