zoukankan      html  css  js  c++  java
  • 练习题之Wait/Notify

    方案一:

    public class PrintABC {
      public static void main(String[] args) {
        AtomicInteger synObj = new AtomicInteger(0);
        Runnable r = new ThreadModel(synObj);
        new Thread(r,"A").start();
        new Thread(r,"B").start();
        new Thread(r,"C").start();
      }
    }
    
    public class ThreadModel implements Runnable {
     public volatile AtomicInteger ato;
      
     public ThreadModel(AtomicInteger ato) {
        this.ato = ato;
     }
    
     public void run() {
      for(int i=0;i<10;i++) {
        synchronized(ato) {
          if(ato.get()%3==0) {
             System.out.println("A);
             ato.set(ato.get()+1);
             ato.notifyAll();
          } else if(ato.get()%3==1) {
             System.out.println("B);
             ato.set(ato.get()+1);
             ato.notifyAll();
          } else if(ato.get()%3==2) {
             System.out.println("C);
             ato.set(ato.get()+1);
             ato.notifyAll();
          } else {
             ato.wait();
          }
        }
      }
     }
    }

    方案二:

    public class printABC {
     
     public static void main(String [] args) {
       AtomicInteger ato = new AtomicInteger(0);
       ThreadModel modelA = new ThreadModel(ato,"A",0);
       ThreadModel modelB = new ThreadModel(ato,"B",0);
       ThreadModel modelC = new ThreadModel(ato,"C",0);
       new Thread(modelA).start();
       new Thread(modelB).start();
       new Thread(modelC).start();
     }
      
    }
    
    public class ThreadModel {
     
      private AtomicInteger ato;
      private String printChar;
      private int flag;
      private int count = 0;
      public ThreadModel(AtomicInteger ato,String printChar,int flag) {
        this.ato = ato;
        this.printChar = printChar;
        this.flag = flag;
      }
     
     public void run() {
        synchronized(ato) {
           while(true) {
              if(ato.get()%3==flag) {
                 System.out.println(printChar);
                 ato.set(ato.get()+1);
                 ato.notifyAll();
                 count++;
                 if(count==10) {
                    break;
                  }
              }else {
                 ato.wait();
              }
           }
        }
     }
     
    }
  • 相关阅读:
    洛谷 P2029 跳舞
    洛谷 P1122 最大子树和
    洛谷 P2015 二叉苹果树
    洛谷 P1651 塔
    洛谷 P1759 通天之潜水
    洛谷 P2763 试题库问题
    洛谷 P2364 胖男孩
    <转>jmeter(十四)HTTP请求之content-type
    <转>jmeter(十三)常见问题及解决方法
    <转>jmeter(十二)关联之正则表达式提取器
  • 原文地址:https://www.cnblogs.com/moonandstar08/p/5503613.html
Copyright © 2011-2022 走看看