Loading

java实现两个线程交替打印0~100

public class jk {
         static volatile int num=0;
         static Object lock=new Object();

   public static void main(String[] args) {

       Runnable task1 = new Task1();
       Runnable task2 = new Task2();
       ExecutorService executorService = Executors.newFixedThreadPool(2);
       executorService.execute(task1);
       executorService.execute(task2);
       System.out.println("oo");
   }

 static    class Task1 implements Runnable{


       @Override
       public void run() {
           while (num<100){
               synchronized (lock){
                   if(num%2 == 0){
                       try {
                           lock.wait();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }

                   System.out.println(Thread.currentThread().getName()+":"+ num++);
                   lock.notifyAll();
               }
           }
       }
   }

 static   class Task2 implements Runnable{

       @Override
       public void run() {
           while (num<100){
               synchronized (lock){
                   if(num%2 != 0){
                       try {
                           lock.wait();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }

                   System.out.println(Thread.currentThread().getName()+":"+ num++);
                   lock.notifyAll();
               }
           }
       }
   }

}


posted @ 2023-09-01 17:39  花园SON  阅读(259)  评论(0编辑  收藏  举报