顺序打印奇数偶数

发布时间 2023-09-04 23:46:20作者: 四十四次日落95
public class code3 {

    private static int count = 0;
    private static final  Object object = new Object();

    public static void main(String[] args) {
        new Thread( new printer(),"偶数线程,").start();
        new Thread( new printer(),"奇数线程,").start();

    }

    static class printer implements Runnable{


        @Override
        public void run() {
            while (count<=10){
                  synchronized (object){
                      System.out.println(Thread.currentThread().getName()+count++);
                      object.notify();

                      if(count<=10){
                          try{
                              //打印后进入等待  等待下次唤醒
                              object.wait();
                          }catch (InterruptedException e){
                              e.printStackTrace();
                          }

                      }
                  }

            }


        }
    }
}