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. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 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. Create a thread by implementing Runnable.
2. Create a thread by extending Thread.
3. Thread ReminderThread Reminder
4. Thread Race DemoThread Race Demo
5. Suggesting when to switch threads with yield()Suggesting when to switch threads with yield()
6. Creating threads with inner classesCreating threads with inner classes
7. The safe way to stop a thread
8. Calling sleep() to wait for a whileCalling sleep() to wait for a while
9. Understanding join()Understanding join()
10. Daemon threads spawn other daemon threadsDaemon threads spawn other daemon threads
11. Daemon threads don't prevent the program from ending.
12. Shows the use of thread priorities.Shows the use of thread priorities.
13. Java 1.5 (5.0) new feature: Thread ScheduleJava 1.5 (5.0) new feature: Thread Schedule
14. Two simple threadsTwo simple threads
15. Simple threads creator Simple threads creator
16. Task
17. SimpleThread using the Runnable interface.SimpleThread using the Runnable interface.
18. Very simple Threading example.Very simple Threading example.
19. Test Override ThreadTest Override Thread
20. Test Override
21. Parallelizing Loops for Multiprocessor Machines
22. Listing All Running Threads in a group
23. Setting priorities on the Thread objects
24. Thread priorities.
25. Use a ThreadGroup.
26. Three Threads TestThree Threads Test
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.