【发布时间】:2021-02-08 18:09:07
【问题描述】:
我有两个班级:
- TestClass,一个通过 Scanner 使用用户输入的类
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 的情况下执行此操作。有什么方法可以做到这一点?
【问题讨论】:
标签: java multithreading parallel-processing synchronization java-threads