代码如下:
package com.java.day19ThreadLock; // 2个线程交替打印数字,线程之间的通信,等待和唤醒 public class ThreadPrint { static int num = 0; public static void main(String[] args) { // 锁对象 Object obj = new Object(); new Thread(){ @Override public void run() { System.out.println("准备开始打印了..."); while (true){ synchronized (obj){ try { // 线程等待 obj.wait(); System.out.println(num); num++; } catch (InterruptedException e) { e.printStackTrace(); } } } } }.start(); new Thread(){ @Override public void run() { while (true){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj){ System.out.println(num); num++; // 唤醒线程 obj.notify(); } } } }.start(); } }
运行如图: