[Java手撕]迴圈列印ABC

Duancf發表於2024-09-01

多執行緒迴圈列印ABC

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static ReentrantLock Lock = new ReentrantLock();
    public static Condition ConditionA = Lock.newCondition();
    public static Condition ConditionB = Lock.newCondition();
    public static Condition ConditionC = Lock.newCondition();

    public static char next = 'A';

    public static void main(String[] args) {
        Thread threadA = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    Lock.lock();
                    try {
                        while (next != 'A') {
                            ConditionA.await();
                        }
                        System.out.println("A");
                        next = 'B';
                        ConditionB.signal();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        Lock.unlock();
                    }
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    Lock.lock();
                    try {
                        while (next != 'B') {
                            ConditionB.await();
                        }
                        System.out.println("B");
                        next = 'C';
                        ConditionC.signal();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        Lock.unlock();
                    }
                }
            }
        });

        Thread threadC = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    Lock.lock();
                    try {
                        while (next != 'C') {
                            ConditionC.await();
                        }
                        System.out.println("C");
                        next = 'A';
                        ConditionA.signal();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        Lock.unlock();
                    }
                }
            }
        });

        threadA.start();
        threadB.start();
        threadC.start();
    }
}

相關文章