[Java手撕]交替列印0-100

Duancf發表於2024-09-01

兩個執行緒交替列印0-100

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


public class Main {

    public static ReentrantLock lock = new ReentrantLock();
    public static Condition odd = lock.newCondition();
    public static Condition even = lock.newCondition();
    public static char flag = 'e';

    public static void main(String[] args) {

        // 0
        new Thread(() -> {
            for (int i = 0; i <= 100; i += 2) {
                lock.lock();
                try {
                    while (flag != 'e') {
                        even.await();
                    }
                    System.out.println(Thread.currentThread().getName() + "列印 " + i);
                    flag = 'o';
                    odd.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }).start();

        // 1
        new Thread(() -> {
            for (int i = 1; i <= 100; i += 2) {
                lock.lock();
                try {
                    while (flag != 'o') {
                        odd.await();
                    }
                    System.out.println(Thread.currentThread().getName() + "列印 " + i);
                    flag = 'e';
                    even.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }).start();
    }
}

相關文章