Presentation is loading. Please wait.

Presentation is loading. Please wait.

Multithreading.

Similar presentations


Presentation on theme: "Multithreading."— Presentation transcript:

1 Multithreading

2 Multithreading Multithreading provide simultaneous execution of two or more parts of a program. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program called a thread. Each thread has a separate path of its execution. Threads are lightweight processes; they share the same address space. In Multithreaded environment, programs make maximum use of CPU so that the idle time can be kept to minimum.

3 Life Cycle of a Thread: A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.

4 Life Cycle of a Thread: New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

5 Life Cycle of a Thread: Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

6 The Thread class and Runnable Interface
A thread can be created in two ways: 1)By extending Thread class 2) By implementing Runnable interface.

7 The Thread class and Runnable Interface
1)By extending Thread class Create a new class that extends Thread class using the following two steps. STEP 1 Need to override run( ) method available in Thread class. This method provides entry point for the thread Following is syntax of run() method: public void run() STEP 2 Once Thread object is created, can start it by calling start( ) method, which executes a call to run( ) method. Following is syntax of start() method: void start();

8 The Thread class and Runnable Interface
1)By extending Thread class Example class Mul extends Thread { public void run(){ System.out.println("My thread is in running state."); } public static void main(String args[]){ Mul obj=new Mul(); obj.start();

9 The Thread class and Runnable Interface
2) By implementing Runnable interface. create a class that implements the Runnable interface. Need to give the definition of run() method. This run method is the entry point for the thread and thread will be alive till run method finishes its execution. Once the thread is created it will start running start() method gets called. Basically start() method calls run() method implicitly.

10 The Thread class and Runnable Interface
2) By implementing Runnable interface. class M implements Runnable{ public void run(){ System.out.println("My thread is in running state."); } public static void main(String args[]){ Thread tobj =new Thread(); tobj.start();

11 The Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons: ■ It is the thread from which other “child” threads will be spawned. ■ Often it must be the last thread to finish execution because it performs various shutdown actions.

12 The Main Thread main thread is created automatically when your program is started It can be controlled through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. Its general form is shown here: static Thread currentThread( )

13 The Main Thread class mainthread {
public static void main(String[] args) Thread t=Thread.currentThread(); System.out.println("current thread "+t); } o/p current thread Thread[main,5,main]

14 The Main Thread o/p Current thread: Thread[main,5,main]
// Controlling the main Thread. class C1 { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); t.setName("popo Thread"); // change the name of the thread System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); System.out.println("Exiting Main Thread"); o/p Current thread: Thread[main,5,main] After name change: Thread[popo Thread,5,main] 5 4 3 2 1 Exiting Main Thread

15 The Main Thread The reference to the current thread (the main thread, in this case) is obtained by calling currentThread( ), and this reference is stored in the local variable t. setName( ) to change the internal name of the thread. Next, a loop counts down from five, pausing one second between each line. The sleep( ) method causes the thread from which it is called to suspend execution for the specified period of milliseconds. The sleep( ) method in Thread might throw an InterruptedException. This would happen if some other thread wanted to interrupt this sleeping one.

16 Thread methods getName(): It is used for Obtaining a thread’s name
getPriority(): Obtain a thread’s priority isAlive(): Determine if a thread is still running join(): Wait for a thread to terminate run(): Entry point for the thread sleep(): suspend a thread for a period of time start(): start a thread by calling its run() method

17 Creating Second Thread
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 second 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."); 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.");

18 Creating Second Thread
Inside NewThread’s constructor, a new Thread object is created by t = new Thread(this, "Demo Thread"); Passing this as the first argument indicates that you want the new thread to call the run( ) method on this object. Next, start( ) is called, which starts the thread of execution beginning at the run( ) method. This causes the child thread’s for loop to begin. After calling start( ), NewThread’s constructor returns to main( ). When the main thread resumes, it enters its for loop. Both threads continue running, sharing the CPU, until their loops finish.

19 Creating Second Thread
The output produced by this program is as follows: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.

20 Creating Multiple Threads
class NewThread implements Runnable { Thread t; String name; NewThread(String s) name=s; // Create a new, thread t = new Thread(this, name); System.out.println(name+" thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() try { for(int i = 5; i > 0; i--) { System.out.println(" Thread: "+name+" "+ i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); System.out.println("Exiting "+name); class ThreadDemo { public static void main(String args[]) { NewThread A=new NewThread("ONE"); // create a new thread NewThread B=new NewThread("TWO ");// create a new thread

21 Creating Multiple Threads
o/p ONE thread: Thread[ONE,5,main] TWO thread: Thread[TWO ,5,main] Thread: ONE 5 Thread: TWO 5 Thread: ONE 4 Thread: TWO 4 Thread: ONE 3 Thread: TWO 3 Thread: ONE 2 Thread: TWO 2 Thread: ONE 1 Thread: TWO 1 Exiting ONE Exiting TWO

22 Creating Multiple Threads with Priority
class NewThread implements Runnable { Thread t; String name; NewThread(String s,int pri) name=s; // Create a new, second thread t = new Thread(this, name); System.out.println(name+" thread: " + t); t.setPriority(pri); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() try { for(int i = 5; i > 0; i--) { System.out.println(" Thread: "+name+" Priority "+t.getPriority()+" "+ i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); System.out.println("Exiting "+name); class ThreadDemo { public static void main(String args[]) { NewThread A=new NewThread("ONE",2); // create a new thread NewThread B=new NewThread("TWO",10);// create a new thread NewThread C=new NewThread("THREE",6);// create a new thread

23 Creating Multiple Threads with Priority

24 Using isAlive( ) and join( )
How can one thread know when another thread has ended? Two ways exist to determine whether a thread has finished. First, can call isAlive( ) on the thread. This method is defined by Thread, and its general form is final boolean isAlive( ) The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise. Second , can call join( ), shown here: final void join( ) throws InterruptedException This method waits until the thread on which it is called terminates. Additional forms of join( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate

25 Using isAlive( ) and join( )
// Using join() to wait for threads to finish. class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { 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 DemoJoin { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); NewThread ob3 = new NewThread("Three"); System.out.println("Thread One is alive: " + ob1.t.isAlive()); System.out.println("Thread Two is alive: " + ob2.t.isAlive()); System.out.println("Thread Three is alive: " + ob3.t.isAlive()); // wait for threads to finish System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); ob3.t.join(); System.out.println("Main thread Interrupted"); System.out.println("Main thread exiting.");

26 Thread priorities Thread priorities are the integers which decide how one thread should be treated with respect to the others. Thread priority decides when to switch from one running thread to another, process is called context switching A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU. A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. To set the priority of the thread setPriority() method is used which is a method of the class Thread Class. In place of defining the priority in integers, can use MIN_PRIORITY, NORM_PRIORITYor MAX_PRIORITY.

27 Thread Synchronization
When start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce result due to concurrency issue. For example if multiple threads try to write within a same file then they may corrupt the data because one of the threads can overrite data or while one thread is opening the same file at the same time another thread might be closing the same file Java object to allow mutual exclusive access of critical section to two threads.

28 Thread Synchronization
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. Following is the general form of the synchronized statement:

29 Thread Synchronization
Synchronized(object) { // statement to be synchronized } Here, the object is a reference to an object whose lock associates with the monitor that the synchronized statement represents.

30 Thread Synchronization
Java synchronized Keyword provides following functionality essential for concurrent programming :  1) synchronized keyword in Java provides locking, which ensures mutual exclusive access of shared resource and prevent data race. 2) synchronized keyword also prevent reordering of code statement by compiler which can cause subtle concurrent issue if we don't use synchronized or volatile keyword. 3) synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock, at this point it reads data from main memory than cache and when it release the lock, it flushes write operation into main memory which eliminates memory inconsistency errors.

31 Thread Synchronization
Example

32 Thread Synchronization


Download ppt "Multithreading."

Similar presentations


Ads by Google