JUC并发编程学习笔记 (3)

顺序打印ABC,一共打印3遍。

代码示例 public class PrintTest { public static void main(String[] args) { //Line是线程操作的共同资源 Line line = new Line(1); new Thread(() -> { for (int i = 0; i < 3; i++) { try { line.printA(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "A").start(); new Thread(() -> { for (int i = 0; i < 3; i++) { try { line.printB(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "B").start(); new Thread(() -> { for (int i = 0; i < 3; i++) { try { line.printC(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "C").start(); } } class Line { private int state; private Lock lock = new ReentrantLock(); private Condition conditionA = lock.newCondition(); private Condition conditionB = lock.newCondition(); private Condition conditionC = lock.newCondition(); public Line(int state) { this.state = state; } public void printA() throws InterruptedException { //判断等待,业务执行,唤醒其他线程 lock.lock(); try { //注意多个线程,即超过2个线程通信时的虚假唤醒问题,这时候不能用if判断,而要用while循环判断 while (state != StateEnum.FIRST.getCode()) { conditionA.await(); } state = StateEnum.SECOND.getCode(); System.out.print("A"); conditionB.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printB() throws InterruptedException { lock.lock(); try { //注意多个线程,即超过2个线程通信时的虚假唤醒问题,这时候不能用if判断,而要用while循环判断 while (state != StateEnum.SECOND.getCode()) { conditionB.await(); } state = StateEnum.THIRD.getCode(); System.out.print("B"); conditionC.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printC() throws InterruptedException { lock.lock(); try { //注意多个线程,即超过2个线程通信时的虚假唤醒问题,这时候不能用if判断,而要用while循环判断 while (state != StateEnum.THIRD.getCode()) { conditionC.await(); } state = StateEnum.FIRST.getCode(); System.out.print("C"); conditionA.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } /** * 输出 * ABCABCABC */ } public enum StateEnum { FIRST(1,"FIRST"), SECOND(2,"SECOND"), THIRD(3,"THIRD"); private int code; private String name; StateEnum(int code, String name) { this.code = code; } public int getCode() { return code; } public String getName() { return name; } } 线程锁执行问题

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyxsxy.html