线程同步
package day12.javaAdvance.homework.Thread; public class ThreadTest { public static void main(String[] args) { Object obj = new Object(); printNumber1 pn = new printNumber1(obj); pn.start(); printChar1 pc = new printChar1(obj); Thread t = new Thread(pc); t.start(); } } class printNumber1 extends Thread { //创建一个临界资源obj Object obj = new Object(); public printNumber1(Object obj) { this.obj = obj; } public void run() { // 同步代码块: synchronized (obj) { for (int i = 1; i <= 26; i++) { System.out.println(2 * i - 1); System.out.println(2 * i); obj.notifyAll();// 释放/唤醒等待队列所有对象 try { obj.wait();// 等待队列 } catch (InterruptedException e) { e.printStackTrace(); } } } } } class printChar1 implements Runnable { Object obj = new Object(); public printChar1(Object obj) { this.obj = obj; } public void run() { // 同步代码块: synchronized (obj) { for (char i = 'A'; i <= 'Z'; i++) { System.out.println(i); obj.notifyAll(); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }