Java Multithreading

52
What is Thread?

description

java multithreading lectures

Transcript of Java Multithreading

  • What is Thread?

  • What is Thread?Definition: A thread is a single sequential flow of control within a program. ORA thread is the smallest unit of processing that can be scheduled by an operating system. ORA thread is a subset of the process. It is termed as a lightweight process, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process

  • What Is a Thread?A thread is like a classic program that starts at point A and executes until it reaches point B.Threads share the same address space and therefore can share both data and code Context switching between threads is usually less expensive than between processes

  • Relation b/w process and threadA thread is a subset of the process.Process is a program in execution Processes have their own address & process is heavy weight process. Threads (Light weight Processes) share the address space of the process that created it.Process can't communicate other processes but thread do it easily A process may also be made up of multiple threads of execution that execute instructions concurrently

  • What is 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. A multithreading is a specialized form of multitasking

  • Thread Architecture

  • Flow of Thread ProgramExtend the java.lang.Thread Class. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor. Invoke the start( ) method on the instance of the class to make the thread eligible for running.

  • Thread Example 1public class A extends Thread{ public void run(){ for(int i=0; i
  • Thread Example 1public class CallThread { public static void main(String[] args) { A a = new A(); a.start(); }}

  • Thread Example 2class MyThread1 extends Thread{ String s=null;

    MyThread1(String s1){ s=s1; start(); } public void run(){ System.out.println(s);for(int i=0; i

  • Thread Example 2public class ExtendThread{ public static void main(String args[]){ MyThread1 m1=new MyThread1("Thread started...."); }}

  • Thread Example 3public class A implements Runnable{ public void run(){ for(int i=0; i
  • Thread Example 3public class CallThread { public static void main(String[] args) { A a = new A(); Thread t = new Thread(a); t.start(); }}

  • Thread program Implement Runnableclass MyThread1 implements Runnable{ Thread t; String s=null; MyThread1(String s1){ s=s1; t=new Thread(this); t.start(); } public void run(){ System.out.println(s);for(int i=0; i
  • Thread program Implement Runnablepublic class RunableThread{ public static void main(String args[]){ MyThread1 m1=new MyThread1("Thread started...."); }}

  • Flow of ProgramA Class implements the Runnable Interface, override the run() method to define the code executed by thread. An object of this class is Runnable Object. Create an object of Thread Class by passing a Runnable object as argument. Invoke the start( ) method on the instance of the Thread class. If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you implement Runnable interface then you can do this.

  • MultiThread Programclass XThread extends Thread {String name;int limit;int wait;XThread(String name, int limit, int wait) {this.name = name;this.limit = limit;this.wait = wait;start();}public void run() {System.out.println(name +" Thread start");for(int i=0; i
  • MultiThread Programpublic class ThreadExample {

    public static void main(String[] args) {XThread thread1 = new XThread("A",10,1000);XThread thread2 = new XThread("B",15,1500);XThread thread3 = new XThread("C",20,2000);for(int i=0; i

  • MultiThread Program Implement Runnableclass XThread implements Runnable {String name;int limit;int wait;Thread t;XThread(String name, int limit, int wait) {this.name = name;this.limit = limit;this.wait = wait;t = new Thread(this, name +" Thread"); t.start(); // Start the thread}public void run() {System.out.println(name +" Thread start");for(int i=0; i
  • MultiThread Program Implement Runnablepublic class ThreadExample {

    public static void main(String[] args) {XThread thread1 = new XThread("A",10,1000);XThread thread2 = new XThread("B",15,1500);XThread thread3 = new XThread("C",20,2000);for(int i=0; i

  • Thread Priorties

  • Thread Priortiesclass PriorityThread extends Thread{int count;public void run(){while(true){++count;}}}

  • Thread Priortiesclass CallPriorityThread {public static void main(String ar[])throws Exception{PriorityThread pt1 = new PriorityThread();PriorityThread pt2 = new PriorityThread();PriorityThread pt3 = new PriorityThread();//pt1.setPriority(Thread.MAX_PRIORITY);pt2.setPriority(Thread.NORM_PRIORITY);pt3.setPriority(Thread.MIN_PRIORITY);pt1.start();pt2.start();pt3.start();Thread.sleep(1000);pt1.stop();pt2.stop();pt3.stop();System.out.println("Max priority thread "+pt1.count);System.out.println("Normal priority thread "+pt2.count);System.out.println("Min priority thread "+pt3.count);}}

  • Thread PriortiesOutput: Max priority thread 646288206Normal priority thread 47287546Min priority thread 0

  • Thread SynchronizationWhen two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time.The process by which this synchronization is achieved is called thread synchronization.

  • Without Synchronizationclass TwoStrings {static void print (String str1, String str2) { System.out.print(str1);try {Thread.sleep(500);} catch (InterruptedException ie) {e.printStackTrace();}System.out.println(str2);}}

  • Without Synchronizationclass PrintStringsThread implements Runnable {String str1, str2;PrintStringsThread(String str1, String str2) {this.str1 = str1; this.str2 = str2;new Thread(this).start();}public void run() {TwoStrings.print(str1, str2);}}

  • Without Synchronizationpublic class ThreadUnsyncDemo {public static void main(String args[]) {new PrintStringsThread (Hello , there.);new PrintStringsThread (How are , you?);new PrintStringsThread (Thank you ,very much!);}}Result:Hello How are Thank you very much!you?there.

  • Thread Synchronizationclass TwoStrings1 {synchronized static void print (String str1, String str2){System.out.print(str1);try{Thread.sleep(1000);} catch (InterruptedException ie) {e.printStackTrace();}System.out.println(str2);}}

  • Thread Synchronizationclass PrintStringsThread1 implements Runnable {String str1, str2;PrintStringsThread1(String str1, String str2) {this.str1 = str1;this.str2 = str2;new Thread(this).start();}public void run() {TwoStrings1.print(str1, str2);}}

  • Thread Synchronizationpublic class ThreadSyncDemo {public static void main(String args[]) {new PrintStringsThread1 (Hello , there.);new PrintStringsThread1 (How are , you?);new PrintStringsThread1 (Thank you ,very much!);}}

    ResultHello there.How are you?Thank you very much!

  • Wait(), notify()Multithreading replaces event loop programming by dividing your tasks into discrete and logical units. Threads also provide a secondary benefit: they do away with polling. Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time. For example, consider the classic queuing problem, where one thread is producing some data and another is consuming it. To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. Clearly, this situation is undesirable.To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized method. wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). notify( ) wakes up the first thread that called wait( ) on the same object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first

  • // An incorrect implementation of a producer and consumer. class Q { int n; synchronized int get() { System.out.println("Got: " + n); return n; } synchronized void put(int n) { this.n = n; System.out.println("Put: " + n); } }

  • // An incorrect implementation of a producer and consumer.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++); } } }

  • // An incorrect implementation of a producer and consumer.class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while(true) { q.get(); } } }

  • // An incorrect implementation of a producer and consumer.class PC { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } }

  • // An incorrect implementation of a producer and consumer.Result:Put: 1 Got: 1 Got: 1 Got: 1 Got: 1 Got: 1 Put: 2 Put: 3 Put: 4 Put: 5 Put: 6 Put: 7 Got: 7

  • wait( ) and notify( )As you can see, after the producer put 1, the consumer started and got the same 1 five times in a row. Then, the producer resumed and produced 2 through 7 without letting the consumer have a chance to consume them.The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both directions, as shown here

  • Wait and Notify Threads class Que1 {int n;boolean flag = false;synchronized int get() {if(!flag)try{wait();}catch (InterruptedException e) {System.out.println(Exception);}System.out.println(Get: +n);flag = false;notify();return n;}

  • Wait and Notify Threads synchronized void put(int n) {if(flag)try{wait();}catch (InterruptedException e) {System.out.println(Exception);}this.n = n;System.out.println(Put: +n);flag = true;notify();}}//end Que1 class

  • Wait and Notify Threads class Producer1 implements Runnable{Que1 q;Producer1(Que1 q){this.q = q;new Thread(this,").start();}public void run() {int i=0;while(i
  • Wait and Notify Threads class Consumer1 implements Runnable{Que1 q;Consumer1(Que1 q){this.q = q;new Thread(this,").start();}public void run() {while(true){q.get();}}}

  • Wait and Notify Threads public class WaitNotifyDemo {public static void main(String args[]) {Que1 q = new Que1();new Producer1(q);new Consumer1(q);}}

  • Wait and Notify Threads Result:Put: 0Get: 0Put: 1Get: 1Put: 2Get: 2Put: 3Get: 3Put: 4Get: 4Put: 5Get: 5Put: 6Get: 6Put: 7Get: 7Put: 8Get: 8Put: 9Get: 9Put: 10Get: 10

  • stop(), suspend() and resume()stop(), suspend() and resume() are the methods used for thread implementation. stop() - terminate the thread execution, Once a thread is stopped, it cannot be restarted with the start() command, since stop() will terminate the execution of a thread. Instead you can pause the execution of a thread with the sleep() method. The thread will sleep for a certain period of time and then begin executing when the time limit is reached. But, this is not ideal if the thread needs to be started when a certain event occurs. In this case, the suspend() method allows a thread to temporarily cease executing. resume() method allows the suspended thread to start again.

  • DeadLockAdeadlockis a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does.In anoperating system, a deadlock is a situation which occurs when a process enters a waitingstatebecause aresourcerequested by it is being held by another waiting process, which in turn is waiting for another resource. If a process is unable to change its state indefinitely because the resources requested by it are being used by other waiting process, then the system is said to be in a deadlockBelow Both processes need both resources. P1 requires additional resource R1, P2 requires additional resource R2; neither process can continue.

  • DeadLockDeadlockdescribes a situation where two or more threads are blocked forever, waiting for each other. Deadlockis the phenomenon when, typically, two threads eachhold an exclusive lock that the other thread needsin order to continue;in principle, there could actually be more threads and locks involved;

  • DeadLock A special type of error that you need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects. For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete. Deadlock is a difficult error to debug for two reasons:

  • Deadlockclass A { synchronized void foo(B b) { String name = Thread.currentThread().getName(); System.out.println(name + " entered A.foo"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("A Interrupted"); } System.out.println(name + " trying to call B.last()"); b.last(); }

    synchronized void last() { System.out.println("Inside A.last"); } }

  • Deadlockclass B { synchronized void bar(A a) { String name = Thread.currentThread().getName(); System.out.println(name + " entered B.bar"); try { Thread.sleep(1000); } catch(Exception e) { System.out.println("B Interrupted"); } System.out.println(name + " trying to call A.last()"); a.last(); }

    synchronized void last() { System.out.println("Inside A.last"); } }

  • Deadlockclass Deadlock implements Runnable { A a = new A(); B b = new B();

    Deadlock() { Thread.currentThread().setName("MainThread"); Thread t = new Thread(this, "RacingThread"); t.start(); a.foo(b); // get lock on a in this thread. System.out.println("Back in main thread"); } public void run() { b.bar(a); // get lock on b in other thread. System.out.println("Back in other thread"); } public static void main(String args[]) { new Deadlock(); } }

  • outputWhen you run this program, you will see the output shown here: MainThread entered A.foo RacingThread entered B.bar MainThread trying to call B.last() RacingThread trying to call A.last()

    Because the program has deadlocked, you need to press CTRL-C to end the program. You can see a full thread and monitor cache dump by pressing CTRL-BREAK on a PC .You will see that RacingThread owns the monitor onb, while it is waiting for the monitor ona. At the same time, MainThread ownsaand is waiting to getb. This program will never complete. As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of the first conditions that you should check for.

    **