大厂面试手撕经典交替输出案例合集(Java)

交替输出两个数组的元素

使用Synchronized wait notify

import java.util.concurrent.CountDownLatch;

public class PrintInTurnTest02 {
    public static void main(String[] args) {
        final Object lock = new Object();
        String a1 = "1234567";
        String a2 = "ABCDEFG";
        char[] digit = a1.toCharArray();
        char[] chars = a2.toCharArray();
        // 通过CountDownLatch控制某个线程先执行
        CountDownLatch latch = new CountDownLatch(1);

        new Thread(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock) {
                for (Character c : digit) {
                    System.out.println(c);
                    try {
                        // 先唤醒在wait,反过来就没法唤醒了
                        lock.notify();
                        lock.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                // 没有这一行虽然输出结果正确但是程序无法终止
                lock.notify();
            }
        }).start();

        new Thread(() -> {
            synchronized (lock) {
                for (Character c : chars) {
                    System.out.println(c);
                    latch.countDown();
                    try {
                        lock.notify();
                        lock.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                lock.notify();
            }
        }).start();

    }
}

使用Reentrantlock await signal

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

public class PrintInTurnTest03 {
    public static void main(String[] args) {
        String a1 = "1234567";
        String a2 = "ABCDEFG";
        char[] digit = a1.toCharArray();
        char[] chars = a2.toCharArray();

        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        CountDownLatch latch = new CountDownLatch(1);

        new Thread(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            try {
                for (char c : digit) {
                    System.out.println(c);
                    condition.signal(); // notify
                    condition.await(); // wait
                }

                condition.signal();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            lock.lock();
            try {
                for (char c : chars) {
                    System.out.println(c);
                    latch.countDown();

                    condition.signal();
                    condition.await();
                }

                condition.signal();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
    }
}


交替打印0-100

使用Reentrantlock await signal AtomicInteger

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintInTurnTest04 {
    public static void main(String[] args) {
        AtomicInteger num = new AtomicInteger(0);
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                while (num.get() < 100) {
                    num.getAndIncrement();
                    System.out.println(Thread.currentThread().getName() + ": " + num);
                    condition.signal();
                    condition.await();
                }

                condition.signal();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            lock.lock();
            try {
                while (num.get() < 100) {
                    num.getAndIncrement();
                    System.out.println(Thread.currentThread().getName() + ": " + num);
                    condition.signal();
                    condition.await();
                }

                condition.signal();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
    }
}


三个线程交替输出ABC

使用ReentrantLock condition

package com.example.interview.multi_thread.print_in_turn;

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

public class PrintInTurnTest05 {
    public static void main(String[] args) {

        Lock lock = new ReentrantLock();
        Condition printA = lock.newCondition();
        Condition printB = lock.newCondition();
        Condition printC = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                while (true) {
                    System.out.println(Thread.currentThread().getId() + "A");
                    printB.signal();
                    printA.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            lock.lock();
            try {
                while (true) {
                    System.out.println(Thread.currentThread().getId() + "B");
                    printC.signal();
                    printB.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            lock.lock();
            try {
                while (true) {
                    System.out.println(Thread.currentThread().getId() + "C");
                    printA.signal();
                    printC.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

    }
}


轮流打印奇偶数

synchronized

package com.example.interview.multi_thread.print_in_turn;

import java.util.concurrent.atomic.AtomicInteger;

public class PrintInTurnTest06 {

    static class PrintOdd implements Runnable {

        AtomicInteger count;
        Object lock;

        public PrintOdd(AtomicInteger count, Object lock) {
            this.count = count;
            this.lock = lock;
        }

        @Override
        public void run() {
            while (count.get() <= 100) {
                synchronized (lock) {
                    if (count.get() % 2 == 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println(Thread.currentThread().getName() + " " + count);
                        count.getAndIncrement();
                        lock.notify();
                    }
                }
            }
        }
    }


    static class PrintEven implements Runnable {

        AtomicInteger count;
        Object lock;

        public PrintEven(AtomicInteger count, Object lock) {
            this.count = count;
            this.lock = lock;
        }

        @Override
        public void run() {
            while (count.get() <= 100) {
                synchronized (lock) {

                    if (count.get() % 2 == 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println(Thread.currentThread().getName() + " " + count);
                        count.getAndIncrement();
                        lock.notify();
                    }
                }
            }
        }
    }


    public static void main(String[] args) {

        Object lock = new Object();
        AtomicInteger count = new AtomicInteger(1);


        new Thread(new PrintEven(count, lock)).start();
        new Thread(new PrintOdd(count, lock)).start();

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值