Multithreading
Multithreading
Multithreading
MULTITHREADING
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. There are two distinct types of multitasking: process-based and thread-based. Processes are heavyweight where as threads are lightweight. Multithreading enables to write very efficient programs because it lets to utilize the idle time that is present in most programs.
THREAD MODEL
Threads exist in several states. A thread can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended. A suspended thread can then be resumed. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated.
// Controlling the main Thread. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); //Prints thread name, priority, name of the group System.out.println("Current thread: " + t); t.setName("My Thread"); //change the thread name System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); //suspends thread } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); 5 } } }
CREATING A THREAD
There
IMPLEMENTING RUNNABLE
The easiest way to create a thread is to create a class that implements the Runnable interface. A class need only to implement a single method called run( )
class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: "+ t); t.start(); // Start the thread } // This is the entry point for the thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: "+ i); Thread.sleep(500); } } catch (InterruptedException e) { 8 System.out.println("Child interrupted."); }
System.out.println("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); 9 } }
EXTENDING THREAD
class NewThread extends Thread { NewThread() { super("Demo Thread");//creating a thread System.out.println("Child thread:"+this); start(); // Start the thread } public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: "+i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } 10 System.out.println("Exiting child thread."); } }
class ExtendThread { public static void main(String args[]) { new NewThread(); // create a thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: "+i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } 11 }
try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name+"Interrupted"); } System.out.println(name + " exiting."); } } class MultiThreadDemo { public static void main(String args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three");
13
try { // wait for other threads to end Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); }
}
OUTPUT: New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] One: 5 Two: 5
14
Three: 5 One: 4 Two: 4 Three: 4 One: 3 Three: 3 Two: 3 One: 2 Three: 2 Two: 2 One: 1 Three: 1 Two: 1 One exiting. Two exiting. Three exiting. Main thread exiting.
15
Thread provides two ways by which you can determine if a thread has ended.
This method returns true if the thread upon which it is called is still running.
USING ISALIVE()
//Use isAlive(). class MyThread implements Runnable { int count; Thread thrd; // Construct a new thread. MyThread(String name) { thrd = new Thread(this, name); count = 0; thrd.start(); // start the thread }
17
// Begin execution of new thread. public void run() { System.out.println(thrd.getName() + " starting."); try { do { Thread.sleep(500); System.out.println("In " + thrd.getName() + ", count is " + count); count++; } while(count < 10); } catch(InterruptedException exc) { System.out.println(thrd.getName()+ " interrupted."); } System.out.println(thrd.getName() + " terminating."); 18 } }
class MoreThreads { public static void main(String args[]) { System.out.println("Main thread starting."); MyThread mt1 = new MyThread("Child #1"); MyThread mt2 = new MyThread("Child #2"); MyThread mt3 = new MyThread("Child #3"); do { System.out.print("."); try { Thread.sleep(100); } catch(InterruptedException exc) { System.out.println("Main thread interrupted."); } } while(mt1.thrd.isAlive()||mt2.thrd.isAlive() ||mt3.thrd.isAlive()); 19 System.out.println("Main thread ending."); } }
USING JOIN(
// Use join().
class MyThread implements Runnable { int count; Thread thrd; // Construct a new thread. MyThread(String name) { thrd = new Thread(this, name); count = 0; thrd.start(); // start the thread }
20
// Begin execution of new thread. public void run() { System.out.println(thrd.getName() + " starting."); try { do { Thread.sleep(500); System.out.println("In "+thrd.getName()+", count is " + count); count++; } while(count < 10); } catch(InterruptedException exc) { System.out.println(thrd.getName()+"interrupted."); } System.out.println(thrd.getName()+"terminating."); 21 } }
class JoinThreads { public static void main(String args[]) { System.out.println("Main thread starting."); MyThread mt1 = new MyThread("Child #1"); MyThread mt2 = new MyThread("Child #2"); MyThread mt3 = new MyThread("Child #3"); try { mt1.thrd.join(); System.out.println("Child #1 joined."); mt2.thrd.join(); System.out.println("Child #2 joined."); mt3.thrd.join(); System.out.println("Child #3 joined."); } catch(InterruptedException exc) { System.out.println("Main thread interrupted."); } System.out.println("Main thread ending."); } }
22
THREAD PRIORITIES
To set a threads priority, use the setPriority( ) method final void setPriority(int level)
The value of level must be within the range MIN_PRIORITY(1) and MAX_PRIORITY(10). To return a thread to default priority, specify NORM_PRIORITY(5). To obtain the current priority setting call the getPriority( ) method final int getPriority()
23
SYNCHRONIZATION
A
process which ensures that a resource is used by only one thread at a time when multiple threads are running. Java provides unique, language-level support for synchronization. There are two ways
GENERAL FORMS
synchronized
method:
statement:
synchronized(object){ // body }
25
class SumArray { private int sum; synchronized int sumArray(int nums[]) { sum = 0; // reset sum for(int i=0; i<nums.length; i++) { sum += nums[i]; System.out.println("Running total for " + Thread.currentThread().getName()+" is "+ sum); try { Thread.sleep(10); // allow task-switch } catch(InterruptedException exc) { System.out.println("Main threadinterrupted."); }
26
} return sum; }
} class MyThread implements Runnable { Thread thrd; static SumArray sa = new SumArray(); int a[]; int answer; MyThread(String name, int nums[]) { thrd = new Thread(this, name); a = nums; thrd.start(); // start the thread }
27
public void run() {// Begin execution of new thread. int sum; System.out.println(thrd.getName() + " starting."); answer = sa.sumArray(a); System.out.println("Sum for "+thrd.getName()+ is "+ answer); System.out.println(thrd.getName() + "terminating."); } } class Sync { public static void main(String args[]) { int a[] = {1, 2, 3, 4, 5}; MyThread mt1 = new MyThread("Child #1", a); MyThread mt2 = new MyThread("Child #2", a); } 28 }
final void wait() throws InterruptedException final void notify() final void notifyAll()
notify( )
notifyAll( )
29
class Q { int n; boolean valueSet = false; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Got: " + n); valueSet = false; notify(); return n; 30 }
synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); } }
31
class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) { q.put(i++); } } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); }
32
public void run() { while(true) { q.get(); } } } class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } }
33