问题描述
我有两个班级:
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");
}
}
可能,对于您的上下文,您必须添加额外的检查等等。