我正在嘗試從多個正在運行的線程訪問變量。我有一個啟動 2 個線程的主類,一個生產者和一個消費者。PRODUCER 線程讀取一個二進制文件。對于該二進制文件中的每一行,生產者線程從中創建一個對象,并通過阻塞隊列將該對象傳遞給消費者線程。CONSUMER 然后獲取通過阻塞隊列傳入的對象,并將該對象中的字段值輸出到文本文件。有時生產者線程正在讀取的二進制文件中存在錯誤。當二進制文件中錯誤太多時,我希望消費者線程將其輸出的txt文件的擴展名更改為.err我的問題:我不知道如何修改消費者線程中生產者線程的值。我一直在讀到我可以使用 volatile 字段。但我不知道在線程之間使用它的正確方法是什么。這是我的代碼的一個非常簡短且不太復雜的示例:public class Main { private volatile static boolean tooManyErrors= false; public static void main(String[] args) { BlockingQueue<binaryObject> queue = new LinkedBlockingQueue<>(null); binaryObject poison = null; new Thread(new Producer(tooManyErrors, queue, poison)).start(); new Thread(new Consumer(tooManyErrors, queue, poison)).start(); }}public class Producer implements Runnable { private final BlockingQueue<binaryObject> queue; private final binaryObject POISON; private boolean tooManyErrors; private int errorsCounter = 0; public Producer(boolean tooManyErrors, BlockingQueue<binaryObject> queue, binaryObject POISON) { this.tooManyErrors = tooManyErrors; this.queue = queue; this.POISON = POISON; } @Override public void run() { try { process(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { while (true) { try { queue.put(POISON); break; } catch (InterruptedException e) { //... } } } } private void process() throws InterruptedException { //here is where all the logic to read the file and create //the object goes in. counts the number of errors in the file //if too many errors, want to change the tooManyErrors to true if(errorsCounter > 100) { tooManyErrors = true; } }}
1 回答

動漫人物
TA貢獻1815條經驗 獲得超10個贊
好的,這里有幾件事。我假設只有一個生產者和一個消費者。如果是這種情況,您可以將類生產者和消費者標記為static. 如果將該類標記為static,則其字段的一個實例將僅存在 - 它將是一個單例。您可以將生產者和消費者的任何字段標記為非私有字段,然后只需訪問這些字段即可。 somethingINeed = Producer.fieldThatIsNotPrivate來自消費者內部,反之亦然。
另一種選擇是保留所需對象的句柄并將其傳遞給構造函數。
Producer p = new Producer(tooManyErrors, queue, poison);
Consumer c = new Consumer(tooManyErrors, queue, poison);
p.setConsumer(c);
c.setProducer(p);
new Thread(p).start();
new Thread(c).start();
您可以為需要共享信息的任何字段創建訪問器。
添加回答
舉報
0/150
提交
取消