两个线程交替打印1~100

//线程拥有的共同资源
class Number{
     int value=1;
     boolean flag=false;  //两个线程交替执行的一个标志
}

class PrintEven implements Runnable{
     Number num;

     public PrintEven(Number num){
         this.num=num;
     }

     public void run(){
          while(num.value<=100){
              //num是同步锁对象
               synchronized(num){
                    if(num.flag){
                        try{
                            num.wait();//wait()函数必须和锁是同一对象
                        }catch(InterruptedException e){
                            e.printStackTrace();
                        }
                    }else{                    
                         System.out.println(Thread.currentThread().getName()+":"+num.value);
                         num.value++;
                         num.flag=true;
                         num.notify();
                    }
               }
          }
     }
}

class PrintOdd implements Runnable{
      Number num;
      
      public PrintOdd(Number num){
           this.num=num;
      }

      public void run(){
            while(num.value<=100){
                  synchronized(num){
                      if(!num.flag){
                           try{
                                num.wait();
                           }catch(InterruptedException e){
                                e.printStackTrace();
                           }
                      }else{
                           System.out.println(Thread.currentThread().getName()+":"+num.value);
                           num.value++;
                           num.flag=false;
                           num.notify();
                      }
                  }
             }
      }
}

public class Solution{
      public static void main(String[] args){
             Number num=new Number();
             PrintOdd po=new PrintOdd(num);
             PrintEven pe=new PrintEven(num);
             Thread tpo=new Thread(po,"Print Odd");
             Thread tpe=new Thread(pe,"Print Even");
             tpo.start();
             tpe.start();
      }
}

 

 posted on 2018-12-17 19:23  会飞的金鱼  阅读(183)  评论(0)    收藏  举报