要按顺序打印结果,可以使用同步机制来确保代码的执行顺序。下面是一个示例解决方法,使用了Java的synchronized关键字来实现同步:
public class SequentialPrinting {
private static final int MAX_COUNT = 10;
private static int count = 1;
private static Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new PrintNumber(1));
Thread thread2 = new Thread(new PrintNumber(2));
Thread thread3 = new Thread(new PrintNumber(3));
thread1.start();
thread2.start();
thread3.start();
}
static class PrintNumber implements Runnable {
private int threadId;
public PrintNumber(int threadId) {
this.threadId = threadId;
}
@Override
public void run() {
synchronized (lock) {
try {
while (count <= MAX_COUNT) {
// 判断当前线程是否可以执行
while (count % 3 != threadId - 1) {
lock.wait();
}
// 执行打印操作
System.out.println("Thread " + threadId + ": " + count);
count++;
// 唤醒其他线程
lock.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
在上面的代码中,我们创建了三个线程,每个线程负责打印不同的数字。在run方法中,我们使用synchronized关键字锁住了共享的锁对象lock,确保每个线程按顺序执行。
每个线程在执行打印操作之前,首先通过while循环检查当前是否轮到该线程执行。如果不是,则调用lock.wait()使线程进入等待状态,直到被唤醒。在打印操作完成后,通过lock.notifyAll()方法唤醒其他线程,让它们有机会执行。
这样,就可以实现按顺序打印结果。在上述示例中,线程1首先执行,然后是线程2,最后是线程3。每个线程依次打印出1到10的数字。
上一篇:按顺序打印
下一篇:按顺序打印前缀树中的所有单词