Ordered Number Printing with Three Threads
Learn this problemProblem statement
Coordinate three actual worker threads to emit every integer from 0 through n, inclusive, in strictly increasing order. Each worker has one designated role:
ZeroThreademits0exactly once.OddThreademits1, 3, 5, ...throughn.EvenThreademits2, 4, 6, ...throughn.
Implement orderedThreadOutput(n, startOrder). Create one real worker for each role. The array startOrder is a permutation of [0,1,2], where 0 means ZeroThread, 1 means OddThread and 2 means EvenThread. Launch them in that order. Launching order does not guarantee execution order; a worker may run immediately, later, or wake up spuriously from a condition wait.
When a worker emits a value, it appends one string to a shared output log in the exact form ThreadName:value, with no spaces. For example, the odd worker emitting three appends "OddThread:3". After all workers terminate, return that log as a String[]. This return value captures the printed sequence for the function judge; do not write the judged result to standard output.
Start all three workers before joining any of them. Each log entry must be appended by its responsible worker, and every eligible value must appear exactly once. Use synchronization to guarantee order for any fair scheduling of those workers. Do not solve the exercise by generating all labels sequentially in the calling thread, sorting an out-of-order log afterward, or repeatedly printing zero between values. For n = 0, the odd and even workers have no values to emit but must still terminate normally.
Assume normal worker creation and a fair scheduler: workers and the calling thread are not externally interrupted or failed. No particular timing or sleep duration may be used to establish ordering. All synchronization state is fresh for each function call.
Function
orderedThreadOutput(n: int, startOrder: int[]) → String[]Examples
Example 1
n = 5startOrder = [2,1,0]return = ["ZeroThread:0","OddThread:1","EvenThread:2","OddThread:3","EvenThread:4","OddThread:5"]The even and odd workers are launched before the zero worker, but neither may emit first. Synchronization produces zero once, followed by alternating odd and positive-even values through five.
Example 2
n = 0startOrder = [1,2,0]return = ["ZeroThread:0"]Only ZeroThread has a value to emit. The other two workers terminate without appending anything, and the function joins all three before returning.
Constraints
0 ≤ n ≤ 200.startOrdercontains each of0,1and2exactly once.- The returned log contains exactly
n + 1entries, ordered by their numeric values.