我目前正在修改香菸吸菸者問題。在下面你可以找到我的代理類。我需要做什麼才能擁有三個線程而不是一個線程?所以會有三個輸出而不是一個。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);
}
}
1.不要擴展Thread,實現Runnable。 2.不要使用wait/notify,而是一個`java.util.concurrency`同步對象 – 2011-12-13 18:58:30