[Java面試]經典手撕

Duancf發表於2024-07-09

多執行緒迴圈列印ABC

方法一:

package org.example;

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

public class PrintABC {

    ReentrantLock lock = new ReentrantLock();
    Condition a = lock.newCondition();
    Condition b = lock.newCondition();
    Condition c = lock.newCondition();

    char ch = 'A';

    public void printA() {
        lock.lock();
        try {
            while (ch != 'A') {
                try {
                    a.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("A");
            ch = 'B';
            b.signal();
        } finally {
            lock.unlock();
        }

    }

    public void printB() {
        lock.lock();
        try {
            while (ch != 'B') {
                try {
                    b.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
            System.out.println("B");
            ch = 'C';
            c.signal();
        } finally {
            lock.unlock();
        }

    }

    public void printC() {
        lock.lock();
        try {
            while (ch != 'C') {
                try {
                    c.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("C");
            ch = 'A';
            a.signal();
        } finally {
            lock.unlock();
        }

    }


}


public class TestPrintABC {

    public static void main(String[] args) {

        PrintABC printABC = new PrintABC();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    printABC.printA();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    printABC.printB();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    printABC.printC();
                }
            }
        }).start();
    }
}

相關文章