Sunteți pe pagina 1din 38

Very simple Threading example.

//: c13:SimpleThread.java // Very simple Threading example. // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2 002 // www.BruceEckel.com. See copyright notice in CopyRi ght.txt. public class SimpleThread extends Thread { private int countDown = 5; private static int threadCount = 0; public SimpleThread() { super("" + ++threadCount); // Store the thread na me 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(); } } ///:~

Thread Reminder

/* From http://java.sun.com/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."); }

Suggesting when to switch threads with yield()

// // // //

: c13:YieldingThread.java Suggesting when to switch threads with yield(). From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 www.BruceEckel.com. 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(); } } ///:~

Thread Race Demo

/* /* * * * * * * * * * * * *

From http://java.sun.com/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); } }

Creating threads with inner classes

// // // //

: c13:ThreadVariations.java Creating threads with inner classes. From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 www.BruceEckel.com. 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(); }

} ///:~

The safe way to stop a thread


// // // // : c13:Stopping.java The safe way to stop a thread. From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 www.BruceEckel.com. 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 } } ///:~

Calling sleep() to wait for a while

// // // //

: c13:SleepingThread.java Calling sleep() to wait for awhile. From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 www.BruceEckel.com. 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(); } } ///:~

Understanding join()

// // // //

: c13:Joining.java Understanding join(). From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 www.BruceEckel.com. 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(); } } ///:~

Daemon threads spawn other daemon threads

// // // //

: c13:Daemons.java Daemon threads spawn other daemon threads. From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 www.BruceEckel.com. 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); } } ///:~

Daemon threads don't prevent the program from ending.


//: c13:SimpleDaemons.java // Daemon threads don't prevent the program from ending. // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 // www.BruceEckel.com. 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(); } } ///:~

Shows the use of thread priorities.

//: c13:SimplePriorities.java // Shows the use of thread priorities. // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 // www.BruceEckel.com. 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); } } ///:~

Daemon threads don't prevent the program from ending.


//: c13:SimpleDaemons.java // Daemon threads don't prevent the program from ending. // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 // www.BruceEckel.com. 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(); } } ///:~

Shows the use of thread priorities.

//: c13:SimplePriorities.java // Shows the use of thread priorities. // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 // www.BruceEckel.com. 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); } } ///:~

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 import import import

java.util.Date; java.security.SecureRandom; java.util.Random; 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 getName(), obj.toString()); } '%s'%n",

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); } }

Java 1.5 (5.0) new feature: Thread Schedule

/* 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 import import import import import

java.io.IOException; java.io.PrintStream; java.util.Date; java.util.concurrent.Executors; java.util.concurrent.ScheduledExecutorService; 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()); }

Two simple threads

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"); }

Simple threads creator

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(); } } }

Task
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) { } }

} }

Test Override Thread

/* 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]); } } }

Test Override
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]);

Listing All Running Threads in a group

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]); }

} }

Setting priorities on the Thread objects


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); } } }

Thread priorities.
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(); } }

Use a ThreadGroup.

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(); } }

Three Threads Test

/* /* * * * * * * * * * * * * * * * *

From http://java.sun.com/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()); }

Java - Threads in Java


Thread is the feature of mostly languages including Java. Threads allow the program to perform multiple tasks simultaneously. Process speed can be increased by using threads because the thread can stop or suspend a specific running process and start or resume the suspended processes. Multitasking or multiprogramming is delivered through the running of multiple threads

concurrently. If your computer does not have multi-processors then the multi-threads really do not run concurrently. This example illustrates how to create a thread and how to implement the thread. In this example we will see that the program prints numbers from 1 to 10 line by line after 5 seconds which has been declared in the sleep function of the thread class. Sleep function contains the sleeping time in millisecond and in this program sleep function has contained 5000 millisecond mean 5 second time. There is sleep function must caught by the InterruptedException. So, this program used theInterruptedException which tells something the user if thread is failed or interrupted. Here is the code of the program : public class Threads{ public static void main(String[] args){ Thread th = new Thread(); System.out.println("Numbers are printing line by line after 5 seconds : "); try{ for(int i = 1;i <= 10;i++) { System.out.println(i); th.sleep(5000); } } catch(InterruptedException e){ System.out.println("Thread interrupted!"); e.printStackTrace(); } } }

Java Multithreading Example with Thread Class


Java MultiThreading Example In this multithreading example, We will use Thread class to extends in main class to run multithreading in java. Multi threading will explain how to use Thread class in java J2EE program and code.

1. MainThreadClass.java

public class MainThreadClass { public static void main(String[] args) { ThreadClass dt1=new ThreadClass("Run"); ThreadClass dt2=new ThreadClass("Thread"); dt1.start(); // this will start thread of object 1 dt2.start(); // this will start thread of object 2 } }
2. ThreadClass.java

public class ThreadClass extends Thread{ String msg; public void run() { for(int i=0;i<=5;i++) { System.out.println("Run method: "+msg); } } ThreadClass(String mg) { msg=mg; } }
Output
Run method: Run Run method: Run Run method: Run

Run method: Thread Run method: Run Run method: Run Run method: Thread Run method: Thread Run method: Thread Run method: Thread Run method: Run Run method: Thread

import java.util.*; import java.util.concurrent.*; public class Main { public static void main(String[] args) { ArrayList x = new ArrayList(); x.add("A"); x.add("B"); x.add("C"); Collection<Callable> callables = new LinkedList<Callable>(); for (String y : x) { callables.add(new Callable() { public Object call() throws Exception { System.out.println(y); } }); } ExecutorService service = newFixedThreadPool(Runtime.getRuntime().availableProcessors()); service.invokeAll(callables); service.shutdown(); } }

S-ar putea să vă placă și