Java new feature: threading : Simple Threads « Threads « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » Threads » Simple ThreadsScreenshots 
Java new feature: threading
Java new feature: threading


/*
License for Java 1.5 'Tiger': A Developer's Notebook
     (O'Reilly) example package

Java 1.5 'Tiger': A Developer's Notebook (O'Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8

You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigInteger;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.Date;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.Callable;

import static java.util.concurrent.TimeUnit.*;


public class ThreadTester {

  private int[] posArray = new int[] {1363425};
  private int[] negArray = new int[] {-2, -8, -3, -9, -10};

  public ThreadTester() {
  }

  public void testBubbleSort(PrintStream outthrows IOException {
    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) { }
  }

  private void printArray(int[] a, PrintStream outthrows IOException {
    for (int n : a) {
      out.println(n);
    }
    out.println();
  }

  public void testQueue(PrintStream outthrows IOException {
    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();
  }

  public void testCallable(PrintStream outthrows IOException {
    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 static void main(String[] args) {
    ThreadTester tester = new ThreadTester();
  
    try {
      tester.testBubbleSort(System.out);
      tester.testQueue(System.out);
      tester.testCallable(System.out);
    catch (Exception e) {
      e.printStackTrace();
    
  }

}

class BubbleSortThread extends Thread {

  private int[] numbers;

  public BubbleSortThread(int[] numbers) {
    setName("Simple Thread");
    setUncaughtExceptionHandler(
      new SimpleThreadExceptionHandler());
    this.numbers = numbers;
  }

  public void run() {
    int index = numbers.length;
    boolean finished = false;
    while (!finished) {
      index--;
      finished = true;
      for (int i=0; i<index; i++) {
        // Create error condition
        if (numbers[i+10) {
          throw new IllegalArgumentException(
            "Cannot pass negative numbers into this thread!");
        }

        if (numbers[i> numbers[i+1]) {
          // swap
          int temp = numbers[i];
          numbers[i= numbers[i+1];
          numbers[i+1= temp;

          finished = false;
        }
      }
    }    
  }
}

class SimpleThreadExceptionHandler implements
    Thread.UncaughtExceptionHandler {

  public void uncaughtException(Thread t, Throwable e) {
    System.err.printf("%s: %s at line %d of %s%n",
        t.getName()
        e.toString(),
        e.getStackTrace()[0].getLineNumber(),
        e.getStackTrace()[0].getFileName());
  }
}

class Consumer extends Thread {
  
  private BlockingQueue q;
  private PrintStream out;

  public Consumer(String name, BlockingQueue q, 
                  PrintStream out) {
    setName(name);
    this.q = q;
    this.out = out;
  }

  public void run() {
    try {
      while (true) {
        process(q.take());
      }
    catch (InterruptedException e) {
      out.printf("%s interrupted: %s", getName(), e.getMessage());
    }
  }

  private void process(Object obj) {
    out.printf("%s processing object:%n         '%s'%n"
                getName(), obj.toString());
  }
}



class Producer extends Thread {

  private BlockingQueue q;
  private PrintStream out;

  public Producer(BlockingQueue q, PrintStream out) {
    setName("Producer");
    this.q = q;
    this.out = out;
  }

  public void run() {
    try {
      while (true) {
        q.put(produce());
      }
    catch (InterruptedException e) {
      out.printf("%s interrupted: %s", getName(), e.getMessage());
    }
  }

  private String produce() {
    while (true) {
      double r = Math.random();

      // Only goes forward 1/10 of the time
      if ((r*10010) {
        String s = String.format("Inserted at %tc"new Date());
        return s;
      }
    }
  }
}
class RandomPrimeSearch implements Callable<BigInteger> {

  private static final Random prng = new SecureRandom();
  private int bitSize;
 
  public RandomPrimeSearch(int bitSize) {
    this.bitSize = bitSize;
  }

  public BigInteger call() {
    return BigInteger.probablePrime(bitSize, prng);
  }
}
           
       
Related examples in the same category
1. Thread ReminderThread Reminder
2. Thread Race DemoThread Race Demo
3. Suggesting when to switch threads with yield()Suggesting when to switch threads with yield()
4. Creating threads with inner classesCreating threads with inner classes
5. The safe way to stop a thread
6. Calling sleep() to wait for a whileCalling sleep() to wait for a while
7. Understanding join()Understanding join()
8. Daemon threads spawn other daemon threadsDaemon threads spawn other daemon threads
9. Daemon threads don't prevent the program from ending.
10. Shows the use of thread priorities.Shows the use of thread priorities.
11. Java 1.5 (5.0) new feature: Thread ScheduleJava 1.5 (5.0) new feature: Thread Schedule
12. Two simple threadsTwo simple threads
13. Simple threads creator Simple threads creator
14. Task
15. SimpleThread using the Runnable interface.SimpleThread using the Runnable interface.
16. Very simple Threading example.Very simple Threading example.
17. Test Override ThreadTest Override Thread
18. Test Override
19. Parallelizing Loops for Multiprocessor Machines
20. Three Threads TestThree Threads Test
w___w__w___.___j__av_a___2__s.c_o__m__ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.