FileDocCategorySizeDatePackage
ThreadTester.javaAPI DocExample2973Tue May 25 09:47:32 BST 2004com.oreilly.tiger.ch10

ThreadTester

public class ThreadTester extends Object

Fields Summary
private int[]
posArray
private int[]
negArray
Constructors Summary
public ThreadTester()


    
  
Methods Summary
public static voidmain(java.lang.String[] args)

    ThreadTester tester = new ThreadTester();
  
    try {
      tester.testBubbleSort(System.out);
      tester.testQueue(System.out);
      tester.testCallable(System.out);
    } catch (Exception e) {
      e.printStackTrace();
    } 
  
private voidprintArray(int[] a, java.io.PrintStream out)

    for (int n : a) {
      out.println(n);
    }
    out.println();
  
public voidtestBubbleSort(java.io.PrintStream out)

    Thread t1 = new BubbleSortThread(posArray);
    t1.start();

    out.println("Testing with postive numbers...");
    // Wait for the thread to complete
    try {
      t1.join();
      printArray(posArray, out);
    } catch (InterruptedException ignored) { }

    Thread t2 = new BubbleSortThread(negArray);
    t2.start();

    out.println("Testing with negative numbers...");
    try {
      t2.join();
      printArray(negArray, out);
    } catch (InterruptedException ignored) { }
  
public voidtestCallable(java.io.PrintStream out)

    ExecutorService service = Executors.newFixedThreadPool(5);
    Future<BigInteger> prime1 = service.submit(new RandomPrimeSearch(512));
    Future<BigInteger> prime2 = service.submit(new RandomPrimeSearch(512));
    Future<BigInteger> prime3 = service.submit(new RandomPrimeSearch(512));

    try {
      BigInteger bigger = (prime1.get().multiply(prime2.get())).multiply(prime3.get());
      out.println(bigger);
    } catch (InterruptedException e) {
      e.printStackTrace(out);
    } catch (ExecutionException e) {
      e.printStackTrace(out);
    }
  
public voidtestQueue(java.io.PrintStream out)

    BlockingQueue queue = new LinkedBlockingQueue(10);
    Producer p = new Producer(queue, out);
    Consumer c1 = new Consumer("Consumer 1", queue, out);
    Consumer c2 = new Consumer("Consumer 2", queue, out);
    Consumer c3 = new Consumer("Consumer 3", queue, out);
    Consumer c4 = new Consumer("Consumer 4", queue, out);

    p.start(); c1.start(); c2.start(); c3.start(); c4.start();
    try {
      MILLISECONDS.sleep(100);
    } catch (InterruptedException ignored) { }

    // Finish up with these threads
    p.stop();
    c1.stop(); c2.stop(); c3.stop(); c4.stop();