/** * 测试wait()方法和notifyAll()方法,wait():线程等待;notify():唤醒线程 * wait()方法和notify()/notifyAll()方法,必须要放到synchronized() {}代码块中,小括号中的对象必须是同一个 */ public class TestSynchronizedWait { // synchronized() {}代码块中小括号里的参数对象 static Object object = new Object(); // 计数器 static int countNum = 0; // 线程1,打印数字 static Thread thread1 = new Thread(){ @Override public void run() { try { // synchronized() {}代码块 synchronized (object) { int i = 1; for (; i < 53; i++, countNum++) { // 每循环两次,线程等待一次 if (countNum == 2) { // 计数器归零 countNum = 0; // 调用wait()之前,先唤醒所有当前对象线程 object.notifyAll(); // 线程等待,释放锁 object.wait(); } System.out.print(i); } // 最后一次线程等待,释放锁 if (i > 52) { object.notifyAll(); object.wait(); } } } catch (Exception e) { e.printStackTrace(); } } }; // 线程2,打印字符 static Thread thread2 = new Thread() { @Override public void run() { try { // 线程thread2等待,目的是先执行线程thread1 thread2.sleep(10); // synchronized() {}代码块 synchronized (object) { // 获取大写英文字符“A” char c = 'A'; int i = 0; // 循环输出26个大写英文字符 for (; i < 26; i++, c++) { System.out.print(c); object.notifyAll(); object.wait(); } } } catch (Exception e) { e.printStackTrace(); } } }; public static void main(String[] args) { // 启动线程,先后顺序无所谓,执行的时候线程1始终先执行,因为线程2在sleep thread2.start(); thread1.start(); } }