1. 程式人生 > 實用技巧 >Thread management Ordering the execution of threads

Thread management Ordering the execution of threads

Implement a method that takes three objects (instances of Thread or its subclasses). The method must start passed objects as threads in a way that the order of their execution goes like this: t3, t2, t1. These threads print secret phrases to the standard output, their output must be always the same.

All given threads must be terminated before the implemented method is completed.

Otherwise, the testing system will give you some hints on throwing exceptions in the main thread, for example:

Exception in thread "main" java.lang.RuntimeException: All threads must be terminated before ending the implemented method

import java.util.List;

class Invoker {

    public static void invokeMethods(Thread t1, Thread t2, Thread t3) throws InterruptedException {
        for (Thread thread : List.of(t3, t2, t1)) {
            thread.start();
            thread.join();
        }
    }
}

import java.util.List;

class Invoker {

    public static void invokeMethods(Thread t1, Thread t2, Thread t3) throws InterruptedException {
        for (var t : List.of(t3, t2, t1)) {
            startThread(t);
        }
    }

    private static void startThread(Thread t) throws InterruptedException {
        t.start();
        t.join();
    }