Creating Threads with Runnable


The method testConcurrency introduces two new things. First, it shows how you can create a thread by passing it an instance of the Runnable interface. Remember that the Runnable interface defines the single method run. The test constructs an anonymous inner class instance of Runnable for each thread. Note that the code in the run methods does not execute until the start methods are called.

The second new thing in testConcurrency is the use of the Thread method join. When you send the message join to a thread, execution in the current thread halts until that thread completes. The code in testConcurrency first waits until t1 completes, then t2, before the test can proceed.

When you execute JUnit, testConcurrency will in all likelihood pass. In a small method, where everything executes quickly, the thread scheduler will probably allot enough time to a thread to execute the entire method before moving on to the next thread. You can force the issue by inserting a pause in the withdraw method:

 public void withdraw(BigDecimal amount) {    if (amount.compareTo(balance) > 0)       return; try {Thread.sleep(1); } catch (InterruptedException e) {}    balance = balance.subtract(amount); } 

You should now see a red bar.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net