2017-07-07 104 views
0
調用同步(通知)的Java工作後

我讀這樣的: How to use wait and notify in Java?代碼沒有使用多線程

我想要實現的等待的例子/通知對生產者/消費者模型在Java中使用線程。

消費者是一個服務器,其中有一個存儲在列表中的對象。可以添加/刪除此列表。

只有消費者服務器存儲了對象(整數),生產者才發送數據(使用PipedInputStream/PipedOutputStream),否則生產者停止。當服務器再次有對象時,生產者開始發送數據。

問題興起,當我打電話下一方法

public void addInteger() { 
     new Thread (new Runnable() { 
     public void run() { 
      try { 
      System.out.println ("Add before size:" + lConsumerClient.size()); 
      lConsumerClient.add((int)(Math.random()*100.0)); 
      synchronized(oSignalExternal) { 
       oSignalExternal.notify(); 
      } 
      System.out.println ("Add after size:" + lConsumerClient.size()); 
      } catch (Exception e) { e.printStackTrace(); } 
     } 
     }).start(); 
    } 

    public void removeFirst() { 
     new Thread (new Runnable() { 
     public void run() { 
      try { 
      System.out.println ("Remove before size:" + lConsumerClient.size()); 
      if (hasInteger()) { 
       lConsumerClient.remove(0); 
      } 
      synchronized(oSignalExternal) { 
       oSignalExternal.notify(); 
      } 
      System.out.println ("Remove after size:" + lConsumerClient.size()); 
      } catch (Exception e) { e.printStackTrace(); } 
     } 
     }).start(); 
    } 

輸出:

Add before size:0 
Add after size:1 
     i:0 ->18 =218 
     i:0 ->18 =218 
Add before size:1 
     i:0 ->18 =218 
     i:1 ->90 =290 
     i:0 ->18 =218 
     i:1 ->90 =290 
Add before size:2 
     i:0 ->18 =218 
     i:1 ->90 =290 
     i:2 ->76 =276 
Add before size:3 
     i:0 ->18 =218 
     i:1 ->90 =290 
     i:2 ->76 =276 
     i:3 ->43 =243 
Remove before size:4 
Remove before size:3 
Remove before size:2 
     i:0 ->43 =243 
     i:0 ->43 =243 
Remove before size:1 
ExtSynchro$ExtClient sleeping 
Remove after size:0 
Remove after size:0 
Remove after size:0 
ExtSynchro$ExtClient sleeping 
Add after size:0 
Add after size:0 
Add after size:0 
Remove after size:0 

等待和通知工作。

我想知道爲什麼調用後:

synchronized(oSignalExternal) { 
    oSignalExternal.notify(); 
} 

不執行任何代碼?

這裏的完整代碼

import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 
import java.util.*; 
import java.util.concurrent.BlockingQueue; 
import java.util.concurrent.ArrayBlockingQueue; 

import javax.swing.*; 
public class ExtSynchro extends JFrame { 

    JButton jbSync = new JButton("Sync"); 
    JButton jbPlus = new JButton("+"); 
    JButton jbMinus = new JButton("-"); 
    JButton jbStop = new JButton("Stop"); 

    Object oSignalExternal = new Object(); 
    ExtServer exConsumerServer; 
    ExtClient exProducerClient; 
    PipedInputStream pSnk = new PipedInputStream(); 
    PipedOutputStream pSrc = new PipedOutputStream(); 
    static final String NL = System.getProperty("line.separator"); 

    public ExtSynchro() { 
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

    jbSync.addActionListener((ActionEvent e) -> { 
     try { pSrc.connect(pSnk); } catch (IOException ex) {} 
     exConsumerServer = new ExtServer(); 
     exProducerClient = new ExtClient(); 
     exConsumerServer.start(); 
     exProducerClient.start(); 
    }); 

    jbPlus.addActionListener((ActionEvent e) -> { 
     exConsumerServer.addInteger(); 
    }); 

    jbMinus.addActionListener((ActionEvent e) -> { 
     exConsumerServer.removeFirst(); 
    }); 

    jbStop.addActionListener((ActionEvent e) -> { 
     exConsumerServer.stopThread(); 
     exProducerClient.stopThread(); 
     exConsumerServer = null; 
     exProducerClient = null; 
    }); 

    JPanel jpButtons = new JPanel(); 
    jpButtons.setLayout(new BoxLayout(jpButtons, BoxLayout.PAGE_AXIS)); 
    jpButtons.add(jbSync); 
    jpButtons.add(jbPlus); 
    jpButtons.add(jbMinus); 
    jpButtons.add(jbStop); 
    add(jpButtons); 
    pack(); 
    } 

    public static void main(String args[]) { 
    EventQueue.invokeLater(() -> { 
     new ExtSynchro().setVisible(true); 
    }); 
    } 

    class ExtClient extends Thread { 
    private volatile boolean bRunning; 

    @Override public void run() { 
     bRunning = true; 
     while (bRunning) { 
     try { 
      synchronized(oSignalExternal) { 
      try { 
       while (exConsumerServer.hasInteger()) { 
       pSrc.write(200); 
       try { Thread.sleep(3000); } catch (InterruptedException ex) { } 
       } 
       System.out.println(getClass().getName() + "\tsleeping"); 
       oSignalExternal.wait(); 
      } catch (InterruptedException e2) {} 
      if (!bRunning) break; // To exit from synchronized 
      } 
     } catch (IOException e) { 
      bRunning = false; 
     } 
     } 
     System.out.println(getClass().getName() + "\tfinishing"); 
    } 

    public void stopThread() { 
     bRunning = false; 
     synchronized(oSignalExternal) { 
     oSignalExternal.notify(); 
     } 
    } 
    }; 

//The Consumer Server. 

    class ExtServer extends Thread { 
    private volatile boolean bRunning; 
    //BlockingQueue<Integer> lConsumerClient =new ArrayBlockingQueue<>(10); 
    java.util.List<Integer> lConsumerClient = Collections.synchronizedList(new ArrayList<>(4)); 


    @Override public void run() { 
     bRunning = true; 
     while (bRunning) { 
     int iRd; 
     try { 
      while ((iRd = pSnk.read()) != -1) { 
      for (int i = 0; i < lConsumerClient.size(); i++) { 
       int n = lConsumerClient.get(i); 
       System.out.println ("\t\ti:" + i + " ->" + n +"\t=" + (n + iRd)); 
      } 
      } 
     } catch (IOException e) {} 
     } 
     System.out.println(getClass().getName() + "\tfinishing"); 
    } 

    public void addInteger() { 
     new Thread (new Runnable() { 
     public void run() { 
      try { 
      System.out.println ("Add before size:" + lConsumerClient.size()); 
      lConsumerClient.add((int)(Math.random()*100.0)); 
      synchronized(oSignalExternal) { 
       oSignalExternal.notify(); 
      } 
      System.out.println ("Add after size:" + lConsumerClient.size()); 
      } catch (Exception e) { e.printStackTrace(); } 
     } 
     }).start(); 
    } 

    public void removeFirst() { 
     new Thread (new Runnable() { 
     public void run() { 
      try { 
      System.out.println ("Remove before size:" + lConsumerClient.size()); 
      if (hasInteger()) { 
       lConsumerClient.remove(0); 
      } 
      synchronized(oSignalExternal) { 
       oSignalExternal.notify(); 
      } 
      System.out.println ("Remove after size:" + lConsumerClient.size()); 
      } catch (Exception e) { e.printStackTrace(); } 
     } 
     }).start(); 
    } 

    public boolean hasInteger() { 
     return lConsumerClient.size() > 0; 
    } 
    public void stopThread() { 
     bRunning = false; 
     try { pSrc.close();pSnk.close(); } catch (IOException e) {} 
    } 
    }; 
} 
+4

這是你期待我們閱讀的很多代碼。請把它剪下來[mcve]。 –

+2

還有:「我是新手」,那麼遠離wait()和notify()。如果你知道自己在做什麼,你可以做出驚人的事情,但是它們很難正確使用。離開這些(實際上大多數多線程),直到你對Java更加紮實。 (我可以誠實地說,我不認爲我曾經需要使用這些實現:'java.util.concurrent'中的更高級別的類很容易正確使用。 –

+0

有沒有一個主要的,什麼會剪切和粘貼完成? – matt

回答

0

本節傷了你的代碼

synchronized(oSignalExternal) { 
     try { 
     while (exConsumerServer.hasInteger()) { 
      pSrc.write(200); 
      try { Thread.sleep(3000); } catch (InterruptedException ex) { } 
     } 
     System.out.println(getClass().getName() + "\tsleeping"); 
     oSignalExternal.wait(); 
     } catch (InterruptedException e2) {} 
     if (!bRunning) break; // To exit from synchronized 
    } 

你不刪除元素,讓你的exConsumerServer總是有元素。使用阻塞隊列。

BlockingQueue<Integer> valuesToTake = new LinkedBlockingQueue(); 

然後你的運行方法變成了。

while (bRunning) { 
    try{ 
     pSrc.write(valuesToTake.take()); 
    } catch (IOException e) { 
     bRunning = false; 
    } 
} 

然後,您只需將整數發送到值並將客戶端發送它們。

+0

你正在執行的@Anita加整數正在EDT上執行,並且它阻止了你的應用程序。您需要從EDT執行該操作。這就是爲什麼你會使用隊列。您向執行程序提交一個操作或將其發佈到隊列中,並由相應的線程處理它。 – matt

+0

謝謝,現在我明白了這個問題。爲此,我改變了這個問題。檢查'BlockingQueue'和'LinkedBlockingQueue'我看不到有些像'ValuesStored.peek(Index)'查看所有存儲的對象而沒有刪除Object ...'take()' 檢索並刪除... – Anita