栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

面试题:java两个线程交替输出

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

面试题:java两个线程交替输出

文章目录
  • 题目
    • 预备知识
    • 答案一(notify、wait)
    • 答案二(LockSupport)
    • 答案三(ReentrantLock)
    • 答案四(LinkedTransferQueue)

题目

一个线程输出字母,一个线程输出数字,两个线程交替输出。
输出结果:1A2B3C4D5E

预备知识

object.notify() :用于唤醒在该对象上等待的其中一个线程
object.notifyAll() :用于唤醒在该对象上等待的所有线程
object.wait():让当前线程释放该对象的锁,并阻塞当前线程

CountDownLatch latch = new CountDownLatch(1):创建一个数量为1的门闩
latch.countDown() : 门闩数量-1
latch.await():等待,直到门闩数量=0

LockSupport.unpark(thread):唤醒thread线程
LockSupport.park():阻塞当前线程

unpark 必须在thread start之后才有用
unpark 在park之前还是之后,作用是一样的,都会重新唤醒线程.

答案一(notify、wait)
import java.util.concurrent.CountDownLatch;

public class Test {
    static Thread threadA,threadB;

	// new CountDownLatch(1),数量为1的门闩
	// 门闩主要用来控制 threadA 先执行
    static CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) {
        char[] a = "12345".toCharArray();
        char[] b = "abcde".toCharArray();

        final Object obj = new Object();

        threadA = new Thread(() -> {
            synchronized (obj){
                for (char c:a){
                    System.out.print(c);
                    // 门闩 -1
                    latch.countDown();
                    try {
                        obj.notify();        // 唤醒threadB
                        obj.wait();          // 阻塞当前线程,并释放锁
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                obj.notify();
            }
        });

        threadB = new Thread(() -> {
            try {
            	// 等待门闩打开(latch.count 为0时打开)
                latch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (obj){
                for (char c:b){
                    System.out.print(c);
                    try {
                        obj.notify();        // 唤醒threadA
                        obj.wait();          // 阻塞当前线程
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                obj.notify();
            }
        });

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

答案二(LockSupport)
import java.util.concurrent.locks.LockSupport;

public class Test {
    static Thread threadA,threadB;

    public static void main(String[] args) {
        char[] a = "12345".toCharArray();
        char[] b = "abcde".toCharArray();

        threadA = new Thread(() -> {
            for (char c:a){
                System.out.print(c);
                LockSupport.unpark(threadB); // 唤醒threadB
                LockSupport.park();          // 阻塞当前线程
            }
        });

        threadB = new Thread(() -> {
            for (char c:b){
                LockSupport.park();
                System.out.print(c);
                LockSupport.unpark(threadA);
            }
        });

        threadA.start();
        threadB.start();
    }
}
答案三(ReentrantLock)
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test {
    static Thread threadA, threadB;

    public static void main(String[] args) {
        char[] a = "12345".toCharArray();
        char[] b = "abcde".toCharArray();

        Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition(); // 队列1
        Condition condition2 = lock.newCondition(); // 队列2


        threadA = new Thread(() -> {

            try {
                lock.lock();
                for (char c : a) {
                    System.out.print(c);
                    condition2.signal(); // 唤醒队列2
                    condition1.await();  // 阻塞当前线程,并释放锁
                }
                condition2.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        });

        threadB = new Thread(() -> {

            try {
                lock.lock();
                for (char c : b) {
                    System.out.print(c);
                    condition1.signal(); // 唤醒队列1
                    condition2.await();  // 阻塞当前线程
                }
                condition1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        });

        threadA.start();
        threadB.start();
    }
}
答案四(LinkedTransferQueue)
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;

public class Test3 {
    static Thread threadA, threadB;

    public static void main(String[] args) {
        char[] a = "12345".toCharArray();
        char[] b = "abcde".toCharArray();

		// TransferQueue同步容器,一旦调用transfer(c)就会阻塞,直到take()取出
        TransferQueue queue = new LinkedTransferQueue<>();

        threadA = new Thread(() -> {

            try {
                for (char c : a) {
                    queue.transfer(c);               // add并阻塞,直到消费者使用take方法从队列中接收消息
                    System.out.print(queue.take());  // 阻塞,直到获取到值
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        threadB = new Thread(() -> {

            try {
                for (char c : b) {
                    System.out.print(queue.take());
                    queue.transfer(c);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        threadA.start();
        threadB.start();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/952901.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号