可以使用两个线程分别打印数字和字母,并使用一个共享变量来控制打印的顺序。以下是一个示例代码:

public class PrintThread {
    private static Object lock = new Object();
    private static int number = 1;
    private static char letter = 'A';

    public static void main(String[] args) {
        Thread numberThread = new NumberThread();
        Thread letterThread = new LetterThread();

        numberThread.start();
        letterThread.start();
    }

    static class NumberThread extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                while (number <= 52) {
                    // 打印数字
                    System.out.print(number++);
                    System.out.print(number++);

                    // 唤醒字母线程
                    lock.notify();

                    try {
                        // 等待字母线程打印完毕
                        if (number <= 52) {
                            lock.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class LetterThread extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                while (letter <= 'Z') {
                    // 打印字母
                    System.out.print(letter++);

                    // 唤醒数字线程
                    lock.notify();

                    try {
                        // 等待数字线程打印完毕
                        if (letter <= 'Z') {
                            lock.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

这里使用一个共享变量 lock 来进行线程间的同步操作。其中,数字线程负责打印数字,并在每次打印完两个数字后唤醒字母线程,然后等待字母线程打印完毕;字母线程负责打印字母,并在每次打印完一个字母后唤醒数字线程,然后等待数字线程打印完毕。

通过这种方式,可以保证数字和字母的交替打印顺序为 "12A34B...5152Z"

java编程:写两个线程一个线程打印1~ 52另一个线程打印A~Z打印顺序是12A34B…5152Z

原文地址: https://www.cveoy.top/t/topic/ihQn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录