2011-12-13 59 views
1

我目前正在修改香菸吸菸者問題。在下面你可以找到我的代理類。我需要做什麼才能擁有三個線程而不是一個線程?所以會有三個輸出而不是一個。Java中的多線程

public class agent extends Thread { 

    private table smokingtable; 

    public agent(table pSmokingtable) 
    { 
     smokingtable = pSmokingtable; 
    } 

    @Override 
    public void run() 
    { 
     while(true) 
     { 
      try { 
       Thread.sleep(5000); 
      } catch (Exception e) {} 
      smokingtable.setAgentElements(); 
      // this triggers the smoker-threads to look at the table 
      output("The Agent puts " + smokingtable.getAgentElements() + table."); 
      // pause the agent while one smoker thread is running 
     } 
    } 


    public synchronized void wake() 
    { 
     try 
     { 
      notify(); 
     } catch(Exception e){} 
    } 


    public synchronized void pause() 
    { 
     try 
     { 
      this.wait(); 
     } catch (Exception e) {} 
    } 

    private void output(String pOutput) 
    { 
     System.out.println(pOutput); 
    } 
} 

我做了這樣的事情,但肯定這是錯誤的。

public class agent extends Thread { 

    private table smokingtable; 

    public agent(table pSmokingtable) 
    { 
     smokingtable = pSmokingtable; 
    } 

    @Override 
    public void run() 
    { 
     while(true) 
     { 
      try { 
       Thread.sleep(5000); 
      } catch (Exception e) {} 
      smokingtable.setAgent1Elements(); 

      output("The Agent 1 puts " + smokingtable.getAgent1Elements()); 

      smokingtable.setAgent2Elements(); 
      output("The Agent 2 puts " + smokingtable.getAgent2Elements()); 

      smokingtable.setAgent3Elements(); 
      output("The Agent 3 puts " + smokingtable.getAgent3Elements()); 
      pause(); 
     } 
    } 


    public synchronized void wake() 
    { 
     try 
     { 
      notify(); 
     } catch(Exception e){} 
    } 


    public synchronized void pause() 
    { 
     try 
     { 
      this.wait(); 
     } catch (Exception e) {} 
    } 

    private void output(String pOutput) 
    { 
     System.out.println(pOutput); 
    } 
} 
+0

1.不要擴展Thread,實現Runnable。 2.不要使用wait/notify,而是一個`java.util.concurrency`同步對象 – 2011-12-13 18:58:30

回答

0

也許我完全誤解了你的問題,但它看起來像你需要重新檢討在Java胎面的基礎知識。 this將是一個很好的開始

在第二個例子中,它看起來像你試圖從同一個線程運行所有三個代理,我想這不是你想要做的。

在您給出的第一個代碼提取中,將代理標識添加爲字段並添加到代理的構造函數,然後將此Id添加到輸出消息。 現在您只需從某處(可能是您的主要方法)創建三個代理實例,然後從那裏調用它們的運行方法。

public static void main(String[] args) { 
for(int i = 0; i < 3; i++) 
    new agent(i).start(); 
} 

看看這個simple example

2

爲了有3個線程,而不是1,你需要創建3個線程,並啓動它們。

在你的情況下,最簡單的方法是這樣的:

Thread agent1 = new agent(); 
Thread agent2 = new agent(); 
Thread agent3 = new agent(); 

agent1.start(); 
agent2.start(); 
agent3.start(); 

agent1.join(); 
agent2.join(); 
agent3.join(); 

做事的更好的辦法是使用ExecutorService的框架,例如的ThreadPoolExecutor。

ExecutorService pool = Executors.newFixedThreadPool(3); 

for (int i = 0; i < 3; ++i) 
{ 
    pool.execute(new agent()); 
} 

// This will wait for your agents to execute 
pool.shutdown();