首页 > 编程语言 > 详细

使用Java实现多个线程轮流显示数字

时间:2019-04-21 19:52:46      阅读:186      评论:0      收藏:0      [点我收藏+]
package helloworld;

class PrintNum implements Runnable{
    int num;
    Thread mythread;
    Object obj;
    
    public PrintNum(int _num,Object _obj){
        num=_num;
        obj=_obj;
        mythread=new Thread(this);
        mythread.start();
    }
    
    public void run(){
        synchronized(obj){
            while(true){
                while(helloworld.nowstate!=num){
                    try{
                        obj.wait();
                    }catch(InterruptedException ie){
                        System.out.println(ie);
                    }
                }
                helloworld.nowstate=(helloworld.nowstate+1)%10;
                System.out.println(num);
                obj.notifyAll();
            }
        }
    }
}

public class helloworld{
    static int nowstate=0;
    public static void main(String []args){
        Object lock=new Object();
        PrintNum obj[]=new PrintNum[10];
        for(int i=0;i<10;i++)
            obj[i]=new PrintNum(i,lock);
    }
}

使用Java实现多个线程轮流显示数字

原文:https://www.cnblogs.com/qpswwww/p/10746288.html

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