You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java多线程按顺序输出需求及代码问题咨询

Fixing Thread Ordering with Safe Shared State

Got it, let's tackle this problem where your threads need to output in order after their random sleep periods. First, let's break down what's missing in your current code:

  • No thread-safe shared variable to track which thread should print next
  • No synchronization mechanism to coordinate when each thread can output
  • A few small bugs in parameter passing and helper methods

Here's the revised solution that fixes all these issues:

Step 1: Main Class (Threadcase)

package threadcase;
import java.util.Random;

public class Threadcase {
    static Random rnd = new Random(System.currentTimeMillis());
    // Thread-safe shared variable to track the current turn (which thread should print next)
    public static int currentTurn = 1;

    public static void main(String[] args) {
        int k = 6;
        for (int i = 1; i <= k; i++) {
            // Fixed parameter order to match the Threadclass constructor
            int sleepSeconds = rnd.nextInt(7); // Generate 0-6 seconds as required
            Threadclass s = new Threadclass("Thread number " + i, i, sleepSeconds, k);
            s.start();
        }
    }
}

Step 2: Thread Class (Threadclass)

package threadcase;

public class Threadclass extends Thread{
    private String msg;
    private int threadNumber; // Unique identifier for this thread (1-6)
    private int sleepSeconds;
    private int totalThreads;

    public Threadclass(String msg, int threadNumber, int sleepSeconds, int totalThreads){
        this.msg = msg;
        this.threadNumber = threadNumber;
        this.sleepSeconds = sleepSeconds;
        this.totalThreads = totalThreads;
    }

    @Override
    public void run() {
        // Sleep for the random 0-6 seconds
        try {
            System.out.println(msg + " is sleeping for " + sleepSeconds + " seconds");
            Thread.sleep(sleepSeconds * 1000);
        } catch (InterruptedException ie) {
            // Don't swallow exceptions - log the issue gracefully
            System.err.println(msg + " was interrupted: " + ie.getMessage());
            return; // Exit thread if interrupted
        }

        // Wait until it's this thread's turn to print
        synchronized (Threadcase.class) {
            while (Threadcase.currentTurn != threadNumber) {
                try {
                    Threadcase.class.wait(); // Pause until notified
                } catch (InterruptedException e) {
                    System.err.println(msg + " was interrupted while waiting: " + e.getMessage());
                    return;
                }
            }

            // Print when it's our turn, including sequence number
            System.out.println(msg + " - " + threadNumber + "th to output");
            Threadcase.currentTurn++;

            // Notify all waiting threads that the turn has updated
            Threadcase.class.notifyAll();
        }
    }
}

Key Explanations:

  • Thread-Safe Shared State: currentTurn is a static variable protected by synchronized (Threadcase.class) to ensure only one thread can modify or check it at a time.
  • Wait/Notify Coordination: After sleeping, each thread checks if it's their turn. If not, they wait on the class monitor. When a thread finishes printing, it increments currentTurn and wakes up all other threads to recheck.
  • Fixed Parameter Issues: The original constructor had mixed-up parameters (you were passing delay as k and vice versa), which is corrected here to match your intended logic.
  • Proper Sleep Range: Changed rnd.nextInt(10)+1 to rnd.nextInt(7) to strictly generate 0-6 seconds as your requirement states.
  • Graceful Exception Handling: We no longer ignore InterruptedException — we log the problem and exit the thread cleanly instead.

When you run this code, even though threads sleep for random durations, they will output in strict order from Thread number 1 to Thread number 6, each clearly marking their output sequence.

内容的提问来源于stack exchange,提问作者QuestionsAndAnswers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:52:31