java多線程實現奇數和偶數的交叉打印


1.實現奇數和偶數的交叉打印

2.打印時間間隔1秒

public class TestThread02 {
  public static void main(String[] args) {
    Thread t1 = new EvenThread();
    Thread t2 = new EvenThread();
    t1.setName("奇數線程");
    t2.setName("偶數線程");

    t1.start();
    t2.start();
  }
}

class EvenThread extends Thread{
  private static int num = 0;
  public void run() {
    while (true) {
      synchronized (Thread.class) {
        System.out.println(getName() + ":" + ++num);
        try {
          Thread.sleep(1000);
          Thread.class.notify();
          Thread.class.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM