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();
        }
      }
    }
  }
}

你可能感兴趣的:(技术)