1. 程式人生 > >JUC學習之執行緒通訊小Demo

JUC學習之執行緒通訊小Demo

按照順序列印執行緒A、B、C,共列印五輪:

public class Test {

    public static void main(String[] args) {
        AlternatePrinting printing = new AlternatePrinting();
        new Thread(() -> {
            for (int i = 1; i <= 5; i++) {
                try {
                    printing.method1(i);
                } catch
(Exception e) { e.printStackTrace(); } } }, "A").start(); new Thread(() -> { for (int i = 1; i <= 5; i++) { try { printing.method2(i); } catch (Exception e) { e.printStackTrace(); } } }, "B"
).start(); new Thread(() -> { for (int i = 1; i <= 5; i++) { try { printing.method3(i); System.out.println("<------------我是可愛的分割線------------->"); } catch (Exception e) { e.printStackTrace(); } } }, "C"
).start(); } } class AlternatePrinting { private int number = 1; private Lock lock = new ReentrantLock(); private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); public void method1(int time) throws Exception { lock.lock(); try { if (number != 1) { condition1.await(); } System.out.println(Thread.currentThread().getName() + "\t" + time); number = 2; // 喚醒2 condition2.signal(); } finally { lock.unlock(); } } public void method2(int time) throws Exception { lock.lock(); try { if (number != 2) { condition2.await(); } System.out.println(Thread.currentThread().getName() + "\t" + time); number = 3; // 喚醒3 condition3.signal(); } finally { lock.unlock(); } } public void method3(int time) throws Exception { lock.lock(); try { if (number != 3) { condition3.await(); } System.out.println(Thread.currentThread().getName() + "\t" + time); number = 1; // 喚醒1 condition1.signal(); } finally { lock.unlock(); } } }