// The working supervisor... public void run() { // Create and start the clerk threads for (Clerk clerk : clerkTeam) { threadPool.submit(clerk); } atWork = true; // We are ready to receive transactions boolean done = false; while (true) { while (inTray.size() == 0) { // No transaction waiting? try { Thread.sleep(200); // then take a break if (inTray.size() != 0) { // If a transaction has been posted break; // ...continue operations } else { // ...otherwise... shutdownClerks(); // ...tell the clerks to go home... return; // ...we are done for the day! } } catch (InterruptedException e) { // Interrupted while idle, so shut down the clerks and return... shutdownClerks(); return; } } Transaction transaction = inTray.remove(0); try { // Processing the transction... System.out.println(this + " working..."); Thread.sleep(100 * (1 + rand.nextInt(5))); // ...takes a while (100 to 500msec) } catch (InterruptedException e) { System.out.println(this + " interrupted while processing transaction. Continuing..."); } // Allocate the transaction to a clerk... done = false; while (true) { // Find a clerk to do the transaction for (Clerk clerk : clerkTeam) { if (done = clerk.doTransaction(transaction)) break; } if (done) { break; } // No clerk was free so wait a while try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println(this + " interrupted waiting for a free clerk. Continuing...\n"); } } } }
private void shutdownClerks() { // Tell the clerks we are done for the day... for (Clerk clerk : clerkTeam) { clerk.end(); } threadPool.shutdown(); try { threadPool.awaitTermination(10L, TimeUnit.SECONDS); } catch (InterruptedException e) { System.out.println(e); } if (threadPool.isTerminated()) { System.out.println("\nAll clerks for " + this + " have completed their tasks.\n"); } else { System.out.println("\nClerks still running - shutting down anyway.\n"); threadPool.shutdownNow(); } }
public void run() { System.out.println("消費者開始消耗整數......"); for (int i = 1; i <= 10; i++) { try { clerk.getProduct(); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } }