2013-11-03 38 views
0

我需要做的是生產者/消費者程序。我需要做一個2生產者線程(第一將繼續發送一個AcionEvent與4 s休息,第二將做10 s休息相同)。消費者線程需要是帶有JTextArea的JFrame。我需要實現ActionPerformedListner來捕捉生產者創建的事件。當我會趕上第一,即使我需要清除JTextArea文本。當我將抓住第二個事件時,我需要用一些文本填充它。我不知道如何發送ActionEvent消費者線程。任何幫助?從主題中捕捉ActionEvents

+1

你介意發表你描述的代碼嗎? –

回答

1

沒有這麼辛苦的好友,第一兩個線程(生產者/消費者)應該在waiting狀態,而這樣做,你需要兩個對象,一個用於信令第一個線程,第二個用於第二個線程。
而不是這裏生產者的兩個線程可能不是必需的。
這樣的事情。

final Object producer=new Object();//used for signaling the thread about the incoming event 
final Object signalConsumer;//used for signaling consumer thread. 
void run(){ 
while(true){//until end of the system life cycle, use a flag, or set the thread daemon 
try{ 
    synchronized(producer){producer.wait();} 
    Thread.sleep(4000);//sleep for 4 s 
    synchronized(consumer){signalConsumer.notify();}//send the first signal to consumer to clear the textbox 
    Thread.sleep(10000);//sleep for 10 seconds 
    synchronized(consumer){signalConsumer.notify();}//send the second signal to consumer for filling the textbox 
}catch(Exception ex){} 
} 
} 

和消費者線程。 final對象signalConsumer = new Object(); //將引用傳遞給生產者線程。

void run(){ 
while(true){ 
try{ 
    synchronized(signalConsumer){signalConsumer.wait();}//waiting for the first signal 
    //clearing textbox, etc... 
    synchronized(signalConsumer){signalConsumer.wait();}//waiting for the second signal 
    //filling the textbox, etc... 
}catch(Exception ex){} 
} 
} 

並在您捕獲事件的UI線程中通知生產者線程。

+0

仍然不明白:/我需要做2個班,1個製作人1爲消費者?應該怎麼看起來像ui線程exacly(在哪裏通知該製作人) – fa1thly

+0

是去兩個類,一個爲專業和其他的騙局。 UI線程通過'actionPerformed()'方法從系統獲取事件,這個方法通知生產者。 – 2013-11-03 21:04:52