java 多个线程按顺序打印字符
1 public class ABCTest { 2 3 private final static Object lock = new Object(); 4 private static int COUNT = 1; 5 private static int NUM = 4; 6 public static void main(String[] args) throws InterruptedException { 7 MyPrint a = new MyPrint(1); 8 MyPrint b = new MyPrint(2); 9 MyPrint c = new MyPrint(3); 10 MyPrint d = new MyPrint(4); 11 a.start(); 12 b.start(); 13 c.start(); 14 d.start(); 15 a.join(); 16 b.join(); 17 c.join(); 18 d.join(); 19 20 } 21 22 private static class MyPrint extends Thread { 23 24 private int name; 25 26 public MyPrint(int name) { 27 this.name = name; 28 } 29 30 @Override 31 public void run() { 32 for (int i = 0; i < 10; i++) { 33 for (int j = 1; j <= NUM; j ++) { 34 if (j == name) { 35 waitAndPrint(); 36 } 37 } 38 39 } 40 } 41 42 private void waitAndPrint() { 43 while (true) { 44 synchronized (lock) { 45 if (COUNT == name) { 46 // System.out.println("count = " + COUNT); 47 print(); 48 COUNT = name % NUM + 1; 49 lock.notifyAll(); 50 break; 51 } else { 52 try { 53 lock.wait(); 54 } catch (InterruptedException e) { 55 e.printStackTrace(); 56 } 57 } 58 } 59 } 60 } 61 62 private void print() { 63 System.out.println((char)(name + 64)); 64 } 65 } 66 }
常见的java多线程面试题,是更好的理解wait notify ,本质是生产者消费者模型。
要思考wait 的时候为什么要用while,而不是if (因为如果用if 方法结束后这个线程就结束了,不能被 block 住)
posted on 2018-08-30 17:58 cococooder 阅读(408) 评论(0) 收藏 举报
浙公网安备 33010602011771号