[英]Sharing a Scanner between two threads
如何在兩個線程之間共享Scanner對象,以便可以在一個線程中將值傳遞給Standard 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中的“掃描”對象,但我不確定。 :)
提前致謝
要在傳遞的實例上顯示它,您需要在類中調用一個將AtomicBoolean
變量設置為true
。 您將必須編寫一個循環並檢查該變量真值的方法。 如果為true
,則立即打印。
另外,請確保您正在synchronize
讀取和寫入線程
您也可以通過在Java中創建自己的事件來完成此操作
從本教程中閱讀有關此方法的所有信息:
您可以通過使用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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.