2016-07-27 62 views
0

我想用兩個線程編寫多線程程序;第一個將在提示「新」命令後更新隨機訪問文件,第二個接受命令「新」或「結束」,並將其發送到第一個線程。我想使用一個由信號量控制的隊列,這是我在下面寫的。我只是不知道如何關聯其他線程。一個線程應該從用戶命令生成字符串並插入到隊列中,另一個線程從隊列中檢索字符串以將它們寫入直接訪問文件。任何人都可以在如何啓動線程中協助編程嗎?我在爲多線程程序創建第二個線程時遇到問題

package multi_threaded_producer_consumer; 
import java.util.concurrent.Semaphore; 

public class MTQueue { 

    private Semaphore sem = new Semaphore(1); 
    private java.util.Queue<String> statQ; 

    public static void main(String[] args) { 

    } 

    public MTQueue(){ 
     statQ = new java.util.LinkedList<String>(); 
    } 

    public void MTPut(String qe) { 
     try { 
      sem.acquire(); 
      statQ.offer(qe); 
     } catch(InterruptedException ex) { 

     } finally { 
      sem.release(); 
     } 
    } 

    public String MTGet() { 
     String retVal = new String(); 
     try { 
      sem.acquire(); 
      retVal = statQ.poll(); 
     } catch(InterruptedException ex) { 

     } finally { 
      sem.release(); 
     } 
     return retVal; 
    } 

} 
+1

你真的只是問如何用Java編寫線程?這是新的線程(myRunnable).start()。 myRunnable是一個帶有運行函數的類,它可以執行你想要的任何線程。如果你問別的東西,試着更清楚。 –

+0

@GabeSechan我把它放在一個單獨的類中,或者在我已經寫過的內容中添加它嗎?這些可能是愚蠢的問題,但我真的不明白使用多線程的理由 – Chief

+0

吞嚥'InterruptedException'(或任何其他異常)是一種壞習慣。如果你不希望你的程序被打斷,並且你不關心被中斷會發生什麼,那麼你最不應該做的就是拋出新的RuntimeException(ex);' –

回答

0

能如何任何人的幫助發出響聲讓線程開始?

當然。使用基本線程,您必須創建一個Runnable類,以便線程運行。這是一個good tutorial on the subject

這裏是爲您的生產代碼的例子:

// queue must be final for the Runnable classes to use it 
final MTQUeue queue = new MTQueue(); 
... 
// create a new producer thread and start it 
new Thread(new Runnable() { 
    public void run() { 
     queue.MTPut("new"); 
     queue.MTPut("end"); 
    } 
}).start(); 
... 
// create a new consumer thread and start it 
new Thread(new Runnable() { 
    public void run() { 
     System.out.println("Got command: " + queue.MTGet()); 
     System.out.println("Got command: " + queue.MTGet()); 
    } 
}).start(); 

夫婦的有關您的代碼中沒有爲了其他意見:

  • 我認爲這是一個學術項目。否則看看LinkedBlockingQueue這是爲你做的。
  • MTPut()MTGet()方法應該可能只是put()get()。 MT是班級名稱。
  • statQ.offer(...)應該可能是statQ.add(...)offer()方法僅適用於有限的隊列。 LinkedQueue不是其中之一。
  • String retVal = new String();new String()不需要,可以刪除。真的,你可以做一個return statQ.poll();,沒有retVal
  • 捕捉InterruptedException ex並忽略它是非常糟糕的做法。當你抓住它,你應該總是至少中斷當前線程:

    } catch(InterruptedException ex) { 
        // always a good pattern to re-interrupt the current thread 
        Thread.currentThread().interrupt(); 
        // since the thread was interrupted we should return or something 
        return;