Java/Threads/Simple Threads

Материал из Java эксперт
Перейти к: навигация, поиск

Calling sleep() to wait for a while

   <source lang="java">

// : c13:SleepingThread.java // Calling sleep() to wait for awhile. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. public class SleepingThread extends Thread {

 private int countDown = 5;
 private static int threadCount = 0;
 public SleepingThread() {
   super("" + ++threadCount);
   start();
 }
 public String toString() {
   return "#" + getName() + ": " + countDown;
 }
 public void run() {
   while (true) {
     System.out.println(this);
     if (--countDown == 0)
       return;
     try {
       sleep(100);
     } catch (InterruptedException e) {
       throw new RuntimeException(e);
     }
   }
 }
 public static void main(String[] args) throws InterruptedException {
   for (int i = 0; i < 5; i++)
     new SleepingThread().join();
 }

} ///:~


 </source>
   
  
 
  



Create a thread by extending Thread.

   <source lang="java">

class MyThread extends Thread {

 int count;
 MyThread() {
   count = 0;
 }
 public void run() {
   System.out.println("MyThread starting.");
   try {
     do {
       Thread.sleep(500);
       System.out.println("In MyThread, count is " + count);
       count++;
     } while (count < 5);
   } catch (InterruptedException exc) {
     System.out.println("MyThread interrupted.");
   }
   System.out.println("MyThread terminating.");
 }

} public class Main {

 public static void main(String args[]) {
   System.out.println("Main thread starting.");
   MyThread mt = new MyThread();
   mt.start();
   do {
     System.out.println("In main thread.");
     try {
       Thread.sleep(250);
     } catch (InterruptedException exc) {
       System.out.println("Main thread interrupted.");
     }
   } while (mt.count != 5);
   System.out.println("Main thread ending.");
 }

}

 </source>
   
  
 
  



Create a thread by implementing Runnable.

   <source lang="java">

class MyThread implements Runnable {

 int count;
 MyThread() {
   count = 0;
 }
 public void run() {
   System.out.println("MyThread starting.");
   try {
     do {
       Thread.sleep(500);
       System.out.println("In MyThread, count is " + count);
       count++;
     } while (count < 5);
   } catch (InterruptedException exc) {
     System.out.println("MyThread interrupted.");
   }
   System.out.println("MyThread terminating.");
 }

} class RunnableDemo {

 public static void main(String args[]) {
   System.out.println("Main thread starting.");
   MyThread mt = new MyThread();
   Thread newThrd = new Thread(mt);
   newThrd.start();
   do {
     System.out.println("In main thread.");
     try {
       Thread.sleep(250);
     } catch (InterruptedException exc) {
       System.out.println("Main thread interrupted.");
     }
   } while (mt.count != 5);
   System.out.println("Main thread ending.");
 }

}

 </source>
   
  
 
  



Creating threads with inner classes

   <source lang="java">

// : c13:ThreadVariations.java // Creating threads with inner classes. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. // Using a named inner class: class InnerThread1 {

 private int countDown = 5;
 private Inner inner;
 private class Inner extends Thread {
   Inner(String name) {
     super(name);
     start();
   }
   public void run() {
     while (true) {
       System.out.println(this);
       if (--countDown == 0)
         return;
       try {
         sleep(10);
       } catch (InterruptedException e) {
         throw new RuntimeException(e);
       }
     }
   }
   public String toString() {
     return getName() + ": " + countDown;
   }
 }
 public InnerThread1(String name) {
   inner = new Inner(name);
 }

} // Using an anonymous inner class: class InnerThread2 {

 private int countDown = 5;
 private Thread t;
 public InnerThread2(String name) {
   t = new Thread(name) {
     public void run() {
       while (true) {
         System.out.println(this);
         if (--countDown == 0)
           return;
         try {
           sleep(10);
         } catch (InterruptedException e) {
           throw new RuntimeException(e);
         }
       }
     }
     public String toString() {
       return getName() + ": " + countDown;
     }
   };
   t.start();
 }

} // Using a named Runnable implementation: class InnerRunnable1 {

 private int countDown = 5;
 private Inner inner;
 private class Inner implements Runnable {
   Thread t;
   Inner(String name) {
     t = new Thread(this, name);
     t.start();
   }
   public void run() {
     while (true) {
       System.out.println(this);
       if (--countDown == 0)
         return;
       try {
         Thread.sleep(10);
       } catch (InterruptedException e) {
         throw new RuntimeException(e);
       }
     }
   }
   public String toString() {
     return t.getName() + ": " + countDown;
   }
 }
 public InnerRunnable1(String name) {
   inner = new Inner(name);
 }

} // Using an anonymous Runnable implementation: class InnerRunnable2 {

 private int countDown = 5;
 private Thread t;
 public InnerRunnable2(String name) {
   t = new Thread(new Runnable() {
     public void run() {
       while (true) {
         System.out.println(this);
         if (--countDown == 0)
           return;
         try {
           Thread.sleep(10);
         } catch (InterruptedException e) {
           throw new RuntimeException(e);
         }
       }
     }
     public String toString() {
       return Thread.currentThread().getName() + ": " + countDown;
     }
   }, name);
   t.start();
 }

} // A separate method to run some code as a thread: class ThreadMethod {

 private int countDown = 5;
 private Thread t;
 private String name;
 public ThreadMethod(String name) {
   this.name = name;
 }
 public void runThread() {
   if (t == null) {
     t = new Thread(name) {
       public void run() {
         while (true) {
           System.out.println(this);
           if (--countDown == 0)
             return;
           try {
             sleep(10);
           } catch (InterruptedException e) {
             throw new RuntimeException(e);
           }
         }
       }
       public String toString() {
         return getName() + ": " + countDown;
       }
     };
     t.start();
   }
 }

} public class ThreadVariations {

 public static void main(String[] args) {
   new InnerThread1("InnerThread1");
   new InnerThread2("InnerThread2");
   new InnerRunnable1("InnerRunnable1");
   new InnerRunnable2("InnerRunnable2");
   new ThreadMethod("ThreadMethod").runThread();
 }

} ///:~


 </source>
   
  
 
  



Daemon threads don"t prevent the program from ending.

   <source lang="java">

//: c13:SimpleDaemons.java // Daemon threads don"t prevent the program from ending. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. public class SimpleDaemons extends Thread {

 public SimpleDaemons() {
   setDaemon(true); // Must be called before start()
   start();
 }
 public void run() {
   while(true) {
     try {
       sleep(100);
     } catch (InterruptedException e) {
       throw new RuntimeException(e);
     }
     System.out.println(this);
   }
 }
 public static void main(String[] args) {
   for(int i = 0; i < 10; i++)
     new SimpleDaemons();
 }

} ///:~


 </source>
   
  
 
  



Daemon threads spawn other daemon threads

   <source lang="java">

// : c13:Daemons.java // Daemon threads spawn other daemon threads. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt.

class Daemon extends Thread {

 private Thread[] t = new Thread[10];
 public Daemon() {
   setDaemon(true);
   start();
 }
 public void run() {
   for (int i = 0; i < t.length; i++)
     t[i] = new DaemonSpawn(i);
   for (int i = 0; i < t.length; i++)
     System.out.println("t[" + i + "].isDaemon() = " + t[i].isDaemon());
   while (true)
     yield();
 }

} class DaemonSpawn extends Thread {

 public DaemonSpawn(int i) {
   start();
   System.out.println("DaemonSpawn " + i + " started");
 }
 public void run() {
   while (true)
     yield();
 }

} public class Daemons {

 public static void main(String[] args) throws Exception {
   Thread d = new Daemon();
   System.out.println("d.isDaemon() = " + d.isDaemon());
   // Allow the daemon threads to
   // finish their startup processes:
   Thread.sleep(1000);
 }

} ///:~


 </source>
   
  
 
  



Java 1.5 (5.0) new feature: Thread Schedule

   <source lang="java">

/* 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.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import static java.util.concurrent.TimeUnit.*; public class ScheduleTester {

 public static void main(String[] args) {
   // Get the scheduler
   ScheduledExecutorService scheduler =
     Executors.newSingleThreadScheduledExecutor();
   // Get a handle, starting now, with a 10 second delay
   final ScheduledFuture<?> timeHandle =
     scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10, SECONDS);    
   // Schedule the event, and run for 1 hour (60 * 60 seconds)
   scheduler.schedule(new Runnable() {
     public void run() {
       timeHandle.cancel(false);
     }
   }, 60*60, SECONDS);
   /**
    * On some platforms, you"ll have to setup this infinite loop to see output
   while (true) { }
    */
 }

} class TimePrinter implements Runnable {

 private PrintStream out;
 public TimePrinter(PrintStream out) {
   this.out = out;
 }
 public void run() {
   out.printf("Current time: %tr%n", new Date());
 }

}


 </source>
   
  
 
  



Java new feature: threading

   <source lang="java">

/* 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[] {1, 3, 6, 3, 4, 2, 5};
 private int[] negArray = new int[] {-2, -8, -3, -9, -10};
 public ThreadTester() {
 }
 public void testBubbleSort(PrintStream out) throws 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 out) throws IOException {
   for (int n : a) {
     out.println(n);
   }
   out.println();
 }
 public void testQueue(PrintStream out) throws 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 out) throws 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+1] < 0) {
         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*100) < 10) {
       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);
 }

}


 </source>
   
  
 
  



Listing All Running Threads in a group

   <source lang="java">

public class Main {

 public static void main(String[] argv) throws Exception {
   ThreadGroup group = Thread.currentThread().getThreadGroup().getParent();
   while (group.getParent() != null) {
     group = group.getParent();
   }
   int numThreads = group.activeCount();
   Thread[] threads = new Thread[numThreads * 2];
   numThreads = group.enumerate(threads, false);
   for (int i = 0; i < numThreads; i++) {
     Thread thread = threads[i];
     System.out.println(thread.getName());
   }
   int numGroups = group.activeGroupCount();
   ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
   numGroups = group.enumerate(groups, false);
   for (int i = 0; i < numGroups; i++) {
     System.out.println(groups[i]);
   }
 }

}

 </source>
   
  
 
  



Parallelizing Loops for Multiprocessor Machines

   <source lang="java">

/* Java Threads, 3rd Edition By Scott Oaks, Henry Wong 3rd Edition September 2004 ISBN: 0-596-00782-5

  • /


 </source>
   
  
 
  



Setting priorities on the Thread objects

   <source lang="java">

public class Main {

 public static void main(String[] args) throws Exception {
   Thread thread1 = new Thread(new TestThread(1));
   Thread thread2 = new Thread(new TestThread(2));
   thread1.setPriority(Thread.MAX_PRIORITY);
   thread2.setPriority(Thread.MIN_PRIORITY);
   thread1.start();
   thread2.start();
   thread1.join();
   thread2.join();
 }

} class TestThread implements Runnable {

 int id;
 public TestThread(int id) {
   this.id = id;
 }
 public void run() {
   for (int i = 1; i <= 10; i++) {
     System.out.println("Thread" + id + ": " + i);
   }
 }

}

 </source>
   
  
 
  



Shows the use of thread priorities.

   <source lang="java">

//: c13:SimplePriorities.java // Shows the use of thread priorities. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt.

public class SimplePriorities extends Thread {

 private int countDown = 5;
 private volatile double d = 0; // No optimization
 public SimplePriorities(int priority) {
   setPriority(priority);
   start();
 }
 public String toString() {
   return super.toString() + ": " + countDown;
 }
 public void run() {
   while(true) {
     // An expensive, interruptable operation:
     for(int i = 1; i < 100000; i++)
       d = d + (Math.PI + Math.E) / (double)i;
     System.out.println(this);
     if(--countDown == 0) return;
   }
 }
 public static void main(String[] args) {
   new SimplePriorities(Thread.MAX_PRIORITY);
   for(int i = 0; i < 5; i++)
     new SimplePriorities(Thread.MIN_PRIORITY);
 }

} ///:~


 </source>
   
  
 
  



Simple threads creator

   <source lang="java">

public class TwoThread extends Thread {

 private Thread creatorThread;
 public TwoThread() {
   creatorThread = Thread.currentThread();
 }
 public void run() {
   for ( int i = 0; i < 10; i++ ) {
     printMsg();
   }
 }
 public void printMsg() {
   Thread t = Thread.currentThread();
   if ( t == creatorThread ) {
     System.out.println("Creator thread");
   } else if ( t == this ) {
     System.out.println("New thread");
   } else {
     System.out.println("Unexpected threads!");
   }
 }
 public static void main(String[] args) {
   TwoThread tt = new TwoThread();
   tt.start();
   for ( int i = 0; i < 10; i++ ) {
     tt.printMsg();
   }
 }

}


 </source>
   
  
 
  



SimpleThread using the Runnable interface.

   <source lang="java">

// : c13:RunnableThread.java // SimpleThread using the Runnable interface. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. public class RunnableThread implements Runnable {

 private int countDown = 5;
 public String toString() {
   return "#" + Thread.currentThread().getName() +
     ": " + countDown;
 }
 public void run() {
   while(true) {
     System.out.println(this);
     if(--countDown == 0) return;
   }
 }
 public static void main(String[] args) {
   for(int i = 1; i <= 5; i++)
     new Thread(new RunnableThread(), "" + i).start();
   // Output is like SimpleThread.java
 }

} ///:~


 </source>
   
  
 
  



Suggesting when to switch threads with yield()

   <source lang="java">

// : c13:YieldingThread.java // Suggesting when to switch threads with yield(). // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. public class YieldingThread extends Thread {

 private int countDown = 5;
 private static int threadCount = 0;
 public YieldingThread() {
   super("" + ++threadCount);
   start();
 }
 public String toString() {
   return "#" + getName() + ": " + countDown;
 }
 public void run() {
   while (true) {
     System.out.println(this);
     if (--countDown == 0)
       return;
     yield();
   }
 }
 public static void main(String[] args) {
   for (int i = 0; i < 5; i++)
     new YieldingThread();
 }

} ///:~


 </source>
   
  
 
  



Task

   <source lang="java">

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Task implements Runnable {

 long n;
 String id;
 private long fib(long n) {
   if (n == 0)
     return 0L;
   if (n == 1)
     return 1L;
   return fib(n - 1) + fib(n - 2);
 }
 public Task(long n, String id) {
   this.n = n;
   this.id = id;
 }
 public void run() {
   Date d = new Date();
   DateFormat df = new SimpleDateFormat("HH:mm:ss:SSS");
   long startTime = System.currentTimeMillis();
   d.setTime(startTime);
   System.out.println("Starting task " + id + " at " + df.format(d));
   fib(n);
   long endTime = System.currentTimeMillis();
   d.setTime(endTime);
   System.out.println("Ending task " + id + " at " + df.format(d)
       + " after " + (endTime - startTime) + " milliseconds");
 }
 public static void main(String[] args) {
   int nThreads = Integer.parseInt(args[0]);
   long n = Long.parseLong(args[1]);
   Thread t[] = new Thread[nThreads];
   for (int i = 0; i < t.length; i++) {
     t[i] = new Thread(new Task(n, "Task " + i));
     t[i].start();
   }
   for (int i = 0; i < t.length; i++) {
     try {
       t[i].join();
     } catch (InterruptedException ie) {
     }
   }
 }

}


 </source>
   
  
 
  



Test Override

   <source lang="java">

import java.util.ArrayList; public class MainClass implements Runnable {

 static class OverrideThreadGroup extends ThreadGroup {
   public OverrideThreadGroup() {
     super("Administrator Alert Group");
   }
   public void uncaughtException(Thread t, Throwable e) {
     alertAdministrator(e);
   }
 }
 public static void alertAdministrator(Throwable e) {
   // Use Java Mail to send the administrator"s pager an email
   System.out.println("Adminstrator alert!");
   e.printStackTrace();
 }
 public static void main(String[] args) {
   ThreadGroup tg = new OverrideThreadGroup();
   Thread t = new Thread(tg, new MainClass());
   t.start();
 }
 public void run() {
   ArrayList al = new ArrayList();
   while (true) {
     al.add(new byte[1024]);
   }
 }

}


 </source>
   
  
 
  



Test Override Thread

   <source lang="java">

/* Java Threads, 3rd Edition By Scott Oaks, Henry Wong 3rd Edition September 2004 ISBN: 0-596-00782-5

  • /

import java.util.*; public class TestOverrideThread implements Runnable {

   static class OverrideExceptionHandler implements Thread.UncaughtExceptionHandler {
       public void uncaughtException(Thread t, Throwable e) {
           alertAdministrator(e);
       }
   }
   public static void alertAdministrator(Throwable e) {
       // Use Java Mail to send the administrator"s pager an email
       System.out.println("Adminstrator alert!");
       e.printStackTrace();
   }
   public static void main(String[] args) {
       Thread t = new Thread(new TestOverrideThread());
       t.setUncaughtExceptionHandler(new OverrideExceptionHandler());
       System.out.println(t.getUncaughtExceptionHandler());
       t.start();
   }
   public void run() {
       ArrayList al = new ArrayList();
       while (true) {
           al.add(new byte[1024]);
       }
   }

}


 </source>
   
  
 
  



The safe way to stop a thread

   <source lang="java">

// : c13:Stopping.java // The safe way to stop a thread. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.util.Timer; import java.util.TimerTask; class CanStop extends Thread {

 // Must be volatile:
 private volatile boolean stop = false;
 private int counter = 0;
 public void run() {
   while (!stop && counter < 10000) {
     System.out.println(counter++);
   }
   if (stop)
     System.out.println("Detected stop");
 }
 public void requestStop() {
   stop = true;
 }

} public class Stopping {

 public static void main(String[] args) {
   final CanStop stoppable = new CanStop();
   stoppable.start();
   new Timer(true).schedule(new TimerTask() {
     public void run() {
       System.out.println("Requesting stop");
       stoppable.requestStop();
     }
   }, 500); // run() after 500 milliseconds
 }

} ///:~


 </source>
   
  
 
  



Thread priorities.

   <source lang="java">

class PriThread extends Thread {

 PriThread(String name, int pri) {
   super(name);
   setPriority(pri);
   start();
 }
 public void run() {
   System.out.println(getPriority());
 }

} public class Main {

 public static void main(String args[]) throws Exception {
   PriThread mt2 = new PriThread("Low Priority", Thread.NORM_PRIORITY - 1);
   PriThread mt1 = new PriThread("High Priority", Thread.NORM_PRIORITY + 1);
   mt1.join();
   mt2.join();
 }

}

 </source>
   
  
 
  



Thread Race Demo

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

public class RaceDemo {

 private final static int NUMRUNNERS = 2;
 public static void main(String[] args) {
   SelfishRunner[] runners = new SelfishRunner[NUMRUNNERS];
   for (int i = 0; i < NUMRUNNERS; i++) {
     runners[i] = new SelfishRunner(i);
     runners[i].setPriority(2);
   }
   for (int i = 0; i < NUMRUNNERS; i++)
     runners[i].start();
 }

} class SelfishRunner extends Thread {

 private int tick = 1;
 private int num;
 public SelfishRunner(int num) {
   this.num = num;
 }
 public void run() {
   while (tick < 400000) {
     tick++;
     if ((tick % 50000) == 0)
       System.out.println("Thread #" + num + ", tick = " + tick);
   }
 }

}


 </source>
   
  
 
  



Thread Reminder

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.util.Timer; import java.util.TimerTask; /**

* Simple demo that uses java.util.Timer to schedule a task to execute once 5
* seconds have passed.
*/

public class Reminder {

 Timer timer;
 public Reminder(int seconds) {
   timer = new Timer();
   timer.schedule(new RemindTask(), seconds * 1000);
 }
 class RemindTask extends TimerTask {
   public void run() {
     System.out.println("Time"s up!");
     timer.cancel(); //Terminate the timer thread
   }
 }
 public static void main(String args[]) {
   System.out.println("About to schedule task.");
   new Reminder(5);
   System.out.println("Task scheduled.");
 }

}


 </source>
   
  
 
  



Three Threads Test

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

public class ThreeThreadsTest {

 public static void main(String[] args) {
   new SimpleThread("Jamaica").start();
   new SimpleThread("Fiji").start();
   new SimpleThread("Bora Bora").start();
 }

} class SimpleThread extends Thread {

 public SimpleThread(String str) {
   super(str);
 }
 public void run() {
   for (int i = 0; i < 10; i++) {
     System.out.println(i + " " + getName());
     try {
       sleep((long) (Math.random() * 1000));
     } catch (InterruptedException e) {
     }
   }
   System.out.println("DONE! " + getName());
 }

}


 </source>
   
  
 
  



Two simple threads

   <source lang="java">

public class TwoThread extends Thread {

 public void run() {
   for (int i = 0; i < 10; i++) {
     System.out.println("New thread");
   }
 }
 public static void main(String[] args) {
   TwoThread tt = new TwoThread();
   tt.start();
   for (int i = 0; i < 10; i++) {
     System.out.println("Main thread");
   }
 }

}


 </source>
   
  
 
  



Understanding join()

   <source lang="java">

// : c13:Joining.java // Understanding join(). // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. class Sleeper extends Thread {

 private int duration;
 public Sleeper(String name, int sleepTime) {
   super(name);
   duration = sleepTime;
   start();
 }
 public void run() {
   try {
     sleep(duration);
   } catch (InterruptedException e) {
     System.out.println(getName() + " was interrupted. "
         + "isInterrupted(): " + isInterrupted());
     return;
   }
   System.out.println(getName() + " has awakened");
 }

} class Joiner extends Thread {

 private Sleeper sleeper;
 public Joiner(String name, Sleeper sleeper) {
   super(name);
   this.sleeper = sleeper;
   start();
 }
 public void run() {
   try {
     sleeper.join();
   } catch (InterruptedException e) {
     throw new RuntimeException(e);
   }
   System.out.println(getName() + " join completed");
 }

} public class Joining {

 public static void main(String[] args) {
   Sleeper sleepy = new Sleeper("Sleepy", 1500), grumpy = new Sleeper(
       "Grumpy", 1500);
   Joiner dopey = new Joiner("Dopey", sleepy), doc = new Joiner("Doc",
       grumpy);
   grumpy.interrupt();
 }

} ///:~


 </source>
   
  
 
  



Use a ThreadGroup.

   <source lang="java">

class MyThread extends Thread {

 boolean stopped;
 MyThread(ThreadGroup tg, String name) {
   super(tg, name);
   stopped = false;
 }
 public void run() {
   System.out.println(Thread.currentThread().getName() + " starting.");
   try {
     for (int i = 1; i < 1000; i++) {
       System.out.print(".");
       Thread.sleep(250);
       synchronized (this) {
         if (stopped)
           break;
       }
     }
   } catch (Exception exc) {
     System.out.println(Thread.currentThread().getName() + " interrupted.");
   }
   System.out.println(Thread.currentThread().getName() + " exiting.");
 }
 synchronized void myStop() {
   stopped = true;
 }

} public class Main {

 public static void main(String args[]) throws Exception {
   ThreadGroup tg = new ThreadGroup("My Group");
   MyThread thrd = new MyThread(tg, "MyThread #1");
   MyThread thrd2 = new MyThread(tg, "MyThread #2");
   MyThread thrd3 = new MyThread(tg, "MyThread #3");
   thrd.start();
   thrd2.start();
   thrd3.start();
   Thread.sleep(1000);
   System.out.println(tg.activeCount() + " threads in thread group.");
   Thread thrds[] = new Thread[tg.activeCount()];
   tg.enumerate(thrds);
   for (Thread t : thrds)
     System.out.println(t.getName());
   thrd.myStop();
   Thread.sleep(1000);
   
   System.out.println(tg.activeCount() + " threads in tg.");
   tg.interrupt();
 }

}

 </source>
   
  
 
  



Very simple Threading example.

   <source lang="java">

//: c13:SimpleThread.java // Very simple Threading example. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. public class SimpleThread extends Thread {

 private int countDown = 5;
 private static int threadCount = 0;
 public SimpleThread() {
   super("" + ++threadCount); // Store the thread name
   start();
 }
 public String toString() {
   return "#" + getName() + ": " + countDown;
 }
 public void run() {
   while(true) {
     System.out.println(this);
     if(--countDown == 0) return;
   }
 }
 public static void main(String[] args) {
   for(int i = 0; i < 5; i++)
     new SimpleThread();
 }

} ///:~


 </source>