- Multiple threads in 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);
- }
- }
- 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 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( );
- public static void main(String[] args) {
- for(int i = 0; i < 3; i++)
- new agent(i).start();
- }