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

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);
	}
}
posted @ 2019-04-21 19:06  YongkangZhang  阅读(342)  评论(0编辑  收藏  举报