微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java使用getState方法与线程同步

如何解决Java使用getState方法与线程同步

我有两个班级:

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();
    }
}
  • Test一个TestClass 提供虚假输入以对其进行测试的类
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 类与 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");
    }
}

可能,对于您的上下文,您必须添加额外的检查等等。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。