Java多线程按顺序输出需求及代码问题咨询
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:
currentTurnis a static variable protected bysynchronized (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
currentTurnand wakes up all other threads to recheck. - Fixed Parameter Issues: The original constructor had mixed-up parameters (you were passing delay as
kand vice versa), which is corrected here to match your intended logic. - Proper Sleep Range: Changed
rnd.nextInt(10)+1tornd.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
相关产品推荐
相关产品推荐

