Java 使用 getState 方法与线程同步

Java synchronizing with thread using getState method

我有两个 classes:

class TestClass {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.print("1: ");
        String one = scan.nextLine();

        System.out.print("2: ");
        String two = scan.nextLine();

        System.out.print("3: ");
        String three = scan.nextLine();
    }
}
public class Test {
    public static void main(String[] args) throws IOException {
        PipedOutputStream inputSimulator = new PipedOutputStream();
        PrintStream inputProvider = new PrintStream(inputSimulator);
        System.setIn(new BufferedInputStream(new PipedInputStream(inputSimulator)));

        Thread thread = new Thread(() -> TestClass.main(new String[]{}));
        thread.start();

        while (thread.getState() != Thread.State.TIMED_WAITING) ;
        inputProvider.println("One given");
        System.out.println("One given");

        while (thread.getState() != Thread.State.TIMED_WAITING) ;
        inputProvider.println("Two given");
        System.out.println("Two given");

        while (thread.getState() != Thread.State.TIMED_WAITING) ;
        inputProvider.println("Three given");
        System.out.println("Three given");
    }
}

我无法让 Test class 与 TestClass 同步。通过同步,我的意思是如果我想在控制台中打印:

1: One given
2: Two given
3: Three given

但是,我得到:

1: One given
Two given
Three given
2: 3:

我使用 while 循环来检查线程的扫描器当前是否正在等待输入。但是,在第一次输入之后,这种检查机制就不起作用了。我需要在不编辑 TestClass 的情况下执行此操作。有什么方法可以做到这一点?

通常依靠线程计时是一个 非常糟糕的主意,但是根据您的评论和限制,我能想到的最好的方法是使用 Thread.sleep 之类的所以:

    public static void main(String[] args) throws IOException, InterruptedException {
        PipedOutputStream inputSimulator = new PipedOutputStream();
        PrintStream inputProvider = new PrintStream(inputSimulator);
        System.setIn(new BufferedInputStream(new PipedInputStream(inputSimulator)));

        Thread thread = new Thread(() -> TestClass.main(new String[]{}));
        thread.start();

        Thread.sleep(1000);
        while (thread.getState() != Thread.State.TIMED_WAITING) ;
        inputProvider.println("One given");
        System.out.println("One given");

        Thread.sleep(1000);
        while (thread.getState() != Thread.State.TIMED_WAITING) ;
        inputProvider.println("Two given");
        System.out.println("Two given");

        Thread.sleep(1000);
        while (thread.getState() != Thread.State.TIMED_WAITING) ;
        inputProvider.println("Three given");
        System.out.println("Three given");
    }
}

可能,对于您的上下文,您将不得不添加额外的检查等等。