使用Java實現多個線程輪流顯示數字
阿新 • • 發佈:2019-04-21
str imp num inter try catch implement void his
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實現多個線程輪流顯示數字