面试官:请用多种方法实现多线程交替打印ABC问题

这篇文章展示了在Java中实现线程同步的不同方法,包括使用`synchronized`关键字、`join`方法、`Lock`接口、`Condition`对象以及`Semaphore`信号量。每个示例都创建了三个线程A,B,C,并演示了如何协调它们的执行顺序,确保特定的打印顺序。这些机制是Java并发编程中的重要工具,用于管理和控制多线程的执行流程。
摘要由CSDN通过智能技术生成
  1. synchronized

下面展示一些 内联代码片

public class PrintLetter_Synchornize {
    private static int count = 0;
    private static Object obj = new Object();

    public static void createThread(String name, int targetNum) {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (obj) {
                    while (count % 3 == targetNum) {
                        System.out.println(Thread.currentThread().getName());
                        count++;
                        obj.notifyAll();
                    }

                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, name).start();
    }

    public static void main(String[] args) {
        createThread("A", 0);
        createThread("B", 1);
        createThread("C", 2);
    }
}
  1. join
public class PrintLetter_Join {

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread a = createThread("A", null);
            Thread b = createThread("B", a);
            Thread c = createThread("C", b);
            a.start();
            b.start();
            c.start();
            c.join();
        }
    }

    public static Thread createThread(String name, Thread prev) {
        return new Thread(() -> {
            if (prev != null) {
                try {
                    prev.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());

            } else {
                System.out.println(Thread.currentThread().getName());
            }
        }, name);
    }
}
  1. Lock
public class PrintLetter_Lock {

    private static Lock lock = new ReentrantLock();
    private static int state = 0;


    public static void main(String[] args) {
        createThread("A", 0);
        createThread("B", 1);
        createThread("C", 2);
    }

    public static void createThread(String name, int targetNum) {
        new Thread(() -> {
            for (int i = 0; i < 10; ) {
                lock.lock();
                try {
                    while (state % 3 == targetNum) {
                        System.out.println(Thread.currentThread().getName());
                        state++;
                        i++;
                    }
                } finally {
                    lock.unlock();
                }
            }
        }, name).start();
    }
}
  1. Lock + Condition
public class PrintLetter_Condition {
    private static Lock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    private static Condition conditionC = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        PrintLetter_Condition task = new PrintLetter_Condition();
        task.createThread("A", conditionA, conditionB);
        Thread.sleep(100L);
        task.createThread("B", conditionB, conditionC);
        task.createThread("C", conditionC, conditionA);

    }

    public void createThread(String name, Condition await, Condition signal) {
        new Thread(() -> {
            lock.lock();
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName());
                    signal.signal();
                    await.await();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, name).start();
    }
}
  1. Semaphore 信号量
public class PrintLetter_Semaphore {
    private static Semaphore semaphoreA = new Semaphore(1);
    private static Semaphore semaphoreB = new Semaphore(0);
    private static Semaphore semaphoreC = new Semaphore(0);

    public static void main(String[] args) throws InterruptedException {
        createThread("A", semaphoreA, semaphoreB);
        createThread("B", semaphoreB, semaphoreC);
        createThread("C", semaphoreC, semaphoreA);
    }

    private static void createThread(String name, Semaphore acquire, Semaphore release) {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    acquire.acquire();
                    System.out.println(Thread.currentThread().getName());
                    release.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, name).start();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值