写数字的 public class PrintNum implements Runnable{ @Override public void run() { synchronized (Object.class){ for (int i = 1; i <=52; i++) { //12A34B56C78D System.out.print(i); if(i% 2 ==0){ Object.class.notifyAll(); //叫醒其他线程 try { Object.class.wait(); //自己睡觉 } catch (InterruptedException e) { throw new RuntimeException(e); } } } } } }
写字母的
public class PrintZimu implements Runnable{ @Override public void run() { synchronized (Object.class){ for (char i = 'A'; i <='Z' ; i++) { System.out.print(i); Object.class.notifyAll(); try { Object.class.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } }
主函数 public class PrintNumZimu { public static void main(String[] args) { PrintNum printNum =new PrintNum(); PrintZimu printZimu = new PrintZimu(); Thread t1 = new Thread(printNum); Thread t2 = new Thread(printZimu); t1.start(); t2.start(); } }
打印结果为
12A34B56C78D910E1112F1314G1516H1718I1920J2122K2324L2526M2728N2930O3132P3334Q3536R3738S3940T4142U4344V4546W4748X4950Y5152Z