如何在两个线程之间共享 Scanner 对象,以便我可以在一个线程中将值传递给标准 i/p 流并在另一个线程中显示?
我创建了两个线程,如下所示:
在Thread1 中,我使用了以下代码:
while(true)
{
//Thread.currentThread().sleep(5000); // if I used this it is printing ABCD
str = System1Class.scan.nextLine();
System.out.println(str);
}
在Thread2我使用下面的代码:
String st = "ABCD";
InputStream is = new ByteArrayInputStream(st.getBytes());
System.setIn(is);
ThreadMainClass.scan = new Scanner(System.in); // here I am trying to refresh the global object "scan"
这里的“扫描”对象是在类 ThreadMainClass 中全局创建的:
public static Scanner scan = new Scanner(System.in);
两个线程都在访问它。我的要求是:我想在从 Thread2 传递的 Thread1 中显示“ABCD”。它正在显示如果我放了一些延迟,以便在 Thread1 中的行之前创建 Scanner 对象:
str = System1Class.scan.nextLine();
但我不希望两个使用任何延迟。那么我有什么办法吗?我想在从 Thread2 传递的那一刻显示“ABCD”。与此同时,Thread1 应该等待来自控制台的数据,即 Thread1 不应该等待来自 Thread2 的任何通知。如果数据是从 Thread2 传递的,只需获取它并打印它,否则它应该只从控制台等待。
我想我需要一种从 Thread2 刷新“扫描”对象的方法,但我不确定。:)
提前致谢