以下是一个可能的解决方案,使用 Java 的多线程机制来实现:
public class PrintNumbers {
private static final int NUM_THREADS = 3;
private static final int NUM_打印NS = 100;
private static int numToPrint = 1;
private static int threadNumToPrint = 1;
private static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
public void run() {
while (numToPrint < NUM_打印NS) {
synchronized (lock) {
if (numToPrint < NUM_打印NS) {
System.out.println(Thread.currentThread().getName() + ": " + numToPrint);
numToPrint++;
}
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
while (threadNumToPrint < NUM_打印NS) {
synchronized (lock) {
if (threadNumToPrint < NUM_打印NS) {
System.out.println(Thread.currentThread().getName() + ": " + threadNumToPrint);
threadNumToPrint++;
}
}
}
}
});
Thread thread3 = new Thread(new Runnable() {
public void run() {
while (threadNumToPrint < NUM_打印NS) {
synchronized (lock) {
if (threadNumToPrint < NUM_打印NS) {
System.out.println(Thread.currentThread().getName() + ": " + threadNumToPrint);
threadNumToPrint++;
}
}
}
}
});
thread1.start();
thread2.start();
thread3.start();
}
}在上面的代码中,我们创建了三个线程,每个线程都循环打印数字。我们使用了一个静态变量 numToPrint 和三个静态变量 threadNumToPrint,这些变量都表示要打印的数字。我们还使用了一个静态的对象 lock 来确保同步和避免竞争条件。在每个线程中,我们使用 synchronized 块来确保每次只有一个线程可以访问共享资源,并打印数字。这样,我们就可以实现三个线程循环打印数字 1 到 100 的需求。