1

如何在两个线程之间共享 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 刷新“扫描”对象的方法,但我不确定。:)

提前致谢

4

2 回答 2

0

要显示它传递的同一个实例,您需要调用类中的一个方法,将AtomicBoolean变量设置为true. 您将必须编写一个循环并检查该变量的真值的方法。如果是true,则立即打印。

还要确保您正在synchronize读取和写入线程

您也可以通过在 Java 中创建自己的事件来做到这一点

从本教程中阅读有关此方法的所有信息:

如何在 Java 中创建自己的事件

于 2012-10-25T12:04:34.607 回答
0

您可以使用 wait() 和 notify() 方法同步 2 个线程。

在全局类中:

Object wh = new Object();

在thread1的代码中:

while(true)
{

//Thread.currentThread().sleep(5000); // if I used this it is printing ABCD
//Wait thread2 to notify
// Prevent IllegalMonitorStateException occurs
synchronized(wh) {
    wh.wait();
}catch (InterruptedException e) {
    e.printStackTrace();
}
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"
//Notify thread1
// Prevent IllegalMonitorStateException occurs
synchronized(wh) {
    wh.notify();
}catch (InterruptedException e) {
    e.printStackTrace();
}

HTH。

于 2012-10-25T12:12:29.790 回答