面试题:写两个线程,一个线程打印1~26,另一个线程打印字母A-Z,交替打印数字和字母

参考代码

public class SpringbootApplication {

    static class PrintRunnable implements Runnable {
        //定义一个锁
        private Object lock;

        public PrintRunnable(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 0; i < 26; i++) {
                    if (Thread.currentThread().getName() == "打印数字") {
                        //打印数字1-26
                        System.out.print((i + 1));
                        // 唤醒其他在等待的线程
                        lock.notifyAll();
                        try {
                            // 让当前线程释放锁资源,进入wait状态
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else if (Thread.currentThread().getName() == "打印字母") {
                        // 打印字母A-Z
                        System.out.print((char) ('A' + i));
                        // 唤醒其他在等待的线程
                        lock.notifyAll();
                        try {
                            // 让当前线程释放锁资源,进入wait状态
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    //测试main方法
    public static void main(String[] args) {
        Object lock = new Object();
        new Thread(new PrintRunnable(lock), "打印数字").start();
        new Thread(new PrintRunnable(lock), "打印字母").start();
    }
}

运行结果如下:
在这里插入图片描述

总结

主要考察的就是waitnotifyAllnotify3个方法的配合使用,以上由于只是两个线程,其实用notify方法也是可以的。

发布了321 篇原创文章 · 获赞 345 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/105455481