转载

华为Java高级面试题:用两个线程,一个输出字母,一个输出数字,交替输出1A2B3C4D...26Z

HSDIS查看Java代码的汇编指令
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssemble


使用 LockSupport.park()and unpark()

public static void main(String[] args) {
        char[] aI = "1234567".toCharArray();
        char[] aC = "ABCDEFG".toCharArray();
        Lock lock = new ReentrantLock();
        Condition conditionT1 = lock.newCondition();
        Condition conditionT2 = lock.newCondition();
        new Thread(() -> {
            try {
                lock.lock();
                
                for (char c : aI) {
                    System.out.print(c);
                    conditionT2.signal();
                    conditionT1.await();
                }
                conditionT2.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();
    }
正文到此结束
本文目录