JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling
Multithreaded Programming
Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads; Implementing runnable; Synchronization; Changing state of the thread; Bounded buffer problems, read-write problem, producer consumer problems.
Introduction Sub unit of a process is handled by a thread. Examples:- Auto save operation as you type in text editor. Computer game which runs music, score, graphics. Animation program.
Threads Thread is similar to a sequential program It has beginning, steps to execute, an end Threads which runs within a program(process) Every thread has at least one thread-primary thread Micro processor allocates memory to the processes that we execute Each process occupies its own address space All the threads in a process share the same address space. Resources( Memory, Devices, Data of program, Environment of a program) are available to all the threads of that program. A thread is also known as a lightweight process or execution context. Because there are fewer overloads on the processor when it switches from one thread to another. Process are heavy weight.
Relationship between Threads and processes
Single Threaded and Multithreaded application
Threads in Java Java provides built-in support for multithreaded programming. 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. Thus, multithreading is a specialized form of multitasking.
Multi Taksing Process based Thread based
Process based multi tasking Process-based multitasking is the feature that allows your computer to run two or more programs concurrently. For example: process-based multitasking enables you to run the Java compiler at the same time that you are using a text editor. In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
Thread based multitaskng In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously. For instance, a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads.
Differences.. Multitasking threads require less overhead than multitasking processes. Processes are heavyweight tasks that require their own separate address spaces. Inter process communication is expensive and limited. Context switching from one process to another is also costly. Threads, on the other hand, are lightweight. They share the same address space and cooperatively share the same heavyweight process. Inter thread communication is inexpensive, and context switching from one thread to the next is low cost.
The Java Thread Model The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading in mind. In fact, Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles.
Single Threaded Application Every program that we can create has at least one thread. We can access this thread using the currentthread() method of the Thread class This method is a static method. Thread thisthread=thread.currentthread():
Example for single thread public class CurrentThread { public static void main(string args[]) { Thread thisthread =Thread.currentThread(); System.out.println("Current Thread"+ thisthread); try { for(int n=0;n<=10;n++) { System.out.println(n); Thread.sleep(1000); catch (InterruptedException e) { System.out.println("Main Thread exception");
Thread Priorities Java assigns to each thread a priority that determines how that thread should be treated with respect to the others. Thread priorities are integers that specify the relative priority of one thread to another. Thread's priority is used to decide when to switch from one running thread to the next. This is called a context switch
Effect of priority A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on pending I/O. A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted
Creating a Thread Extending the Thread class Using Runnable class
Thread class methods Method getname getpriority isalive join run sleep start Description Obtain a thread's name. Obtain a thread's priority Determine if a thread is still running. Wait for a thread to terminate. Entry point for the thread. Suspend a thread for a period of time. Start a thread by calling its run method.
Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of the program The main thread is important for two reasons: It is the thread from which other "child" threads will be spawned. It must be the last thread to finish execution. When the main thread stops, program terminates. Although the main thread is created automatically when your program is started, it can be controlled through a Thread object.
First program revisted.. public class CurrentThread { public static void main(string args[]) { Thread thisthread =Thread.currentThread(); System.out.println("Current thread: " + thisthread ); thisthread.setname("my Thread"); System.out.println("Current Thread"+ thisthread); Try { for(int n=0;n<=5;n++){ System.out.println("Hello"); Thread.sleep(1000); catch (InterruptedException e) {System.out.println("Main Thread exception");
About the program a reference to the current thread (the main thread, in this case) is obtained by calling currentthread( ) This reference is stored in the local variable thisthread The program then calls setname( ) to change the internal name of the thread. Next, a loop counts down from five, pausing one second between each line. The pause is accomplished by the sleep( ) method. The argument to sleep( ) specifies the delay period in milliseconds. The sleep( ) method in Thread might throw an interruptedexception.
Editing and Compilation Create new Project (Optional) Add new Java source file Run as (Similar to compiling java class files)
Result Current thread: Thread[main,5,main] Current ThreadThread[My Thread,5,main] Hello Hello Hello Hello Hello Hello
About sleep method The sleep( ) method causes the thread from which it is called to suspend execution for the specified period of milliseconds. Its general form is shown here: static void sleep(long milliseconds) throws InterruptedException
Creating thread Java defines two ways in which this can be accomplished: implement the Runnable interface. extend the Thread class, itself.
Implementing Runnable You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) Inside run( ), you will define the code that constitutes the new thread. Then instantiate an object of type Thread from within that class. Thread defines several constructors: Thread(Runnable threadob, String threadname) threadob is an instance of a class that implements the Runnable interface. After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. start( ) executes a call to run( ).
Child thread: to generate 10 numbers class ChildThread implements Runnable { Thread t; ChildThread() { t = new Thread(this, New Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread public void run(){// This is the entry point for the second thread. 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.");
Main thread public class RunnableThreadDemo { public static void main(string[] args) { new ChildThread(); // create a new thread System.out.println("Main thread exiting.");
Extending Thread The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.
Example: Extend // Create a second thread by extending Thread class NewThread extends Thread { Thread t; NewThread() { t = new Thread(this, Child Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread public void run()//entry point { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); catch (InterruptedException e) { System.out.println("Exiting child thread.");
Main Thread public class ExtendThreadDemo { public static void main(string args[]) { new NewThread(); // create a new thread System.out.println("Main thread exiting.");
Thread creation using Extend and Runnable two in one example
class ChildThreadRunnable implements Runnable { Thread t1; ChildThreadRunnable() { t1 = new Thread(this, Thread 1"); t1.start(); // Start the thread public void run()//entry point { try { System.out.println("Hello from Runnable Child Thread"); Thread.sleep(5000); catch (InterruptedException e) { System.out.println("Exiting child thread 1!");
class ChildThreadExtend extends Thread { Thread t2; ChildThreadExtend() { t2 = new Thread(this, "Even Thread"); t2.start(); // Start the thread public void run()//entry point { try { System.out.println("Hello from Extended Child Thread"); Thread.sleep(1000); catch (InterruptedException e) { System.out.println("Exiting child thread 2!");
Which approach is better Runnable method Because thread may extend from some other class in such case its better practice to implement runnable method Ex: Userdefined Applet class extend from Applet class to make it as thread use Runnable as multiple extend is not supported by Java Wrong : MyApplet extend Applet extend Thread Right: MyApplet extend Applet implements Runnable
Multiple threads: to handle even and odd number generation Problem statement Design multiple threads using java to demonstrate even and odd number generation each handled by different thread. Two threads with different purposes
Child thread: Even class EvenThread1 implements Runnable { Thread t; EvenThread1() { t = new Thread(this, Even Thread"); t.start(); // Start the thread // This is the entry point for the second thread. public void run()//assign work here { try { for(int i =0; i <=10 ; i++) { if(i%2==0) System.out.println("Next Even Number:" + i); Thread.sleep(500); catch (InterruptedException e) {System.out.println("Child interrupted."); System.out.println("Exiting Even child thread.");
Child thread: Odd class OddThread1 implements Runnable { Thread t; OddThread1() { t = new Thread(this, "Odd Thread"); t.start(); // Start the thread // This is the entry point for the second thread. public void run()//assign work here { try { for(int i =0; i <=10 ; i++) { if(i%2!=0) System.out.println("Next Odd Number:" + i); Thread.sleep(500); catch (InterruptedException e) {System.out.println("Child interrupted."); System.out.println("Exiting Odd child thread.");
Main Thread public class MultiThread { public static void main(string args[]) { new EvenThread1(); // create a new thread new OddThread1(); // create a new thread System.out.println("Main thread exiting.");
The Runnable interface consists of a single method, run(), which is executed when the thread is activated. public class thread implements Runnable {...........;
Multiple threads: to handle even and odd number generation Problem statement Design multiple threads using java to demonstrate even and odd number generation each handled by different thread. Two threads with same purposes
class Thread1 implements Runnable { Thread t; String name; int delay; Thread1(String name,int delay) { t = new Thread(this, name); this.name=name; this.delay=delay; t.start(); // Start the thread public class MultiThread2 { public static void main(string args[]) { new Thread1("First",1000); new Thread1("Second",2000); new Thread1("Third",3000); System.out.println("Main thread exiting."); // This is the entry point for the second thread. public void run()//assign work here { try { for(int i =1; i <=5 ; i++) {System.out.println("Next Number:" + i+ " generated by :"+name); Thread.sleep(delay); catch (InterruptedException e) { System.out.println("Exiting Even child thread.");
One instance of output Next Number:1 generated by :Second Next Number:1 generated by :First Main thread exiting. Next Number:1 generated by :Third Next Number:2 generated by :First Next Number:3 generated by :First Next Number:2 generated by :Second Next Number:4 generated by :First Next Number:2 generated by :Third Next Number:3 generated by :Second Next Number:5 generated by :First Exiting child thread: First Next Number:4 generated by :Second Next Number:3 generated by :Third Next Number:5 generated by :Second Next Number:4 generated by :Third Exiting child thread: Second Next Number:5 generated by :Third Exiting child thread :Third * This need not be same always
Life Cycle of Thread 1. New 2. Runnable 3. Dead 4. Blocked
Life cycle of a Thread
Blocked thread Thread goes to sleep by calling the sleep The thread calls an operation that is blocking on I/O The tries to acquire a lock that is currently held by another thread. The thread waits for a condition Any other can call suspend method of the thread
Blocked state to active If a thread has been put to sleep, the specified number of msec must expire. If a thread is waiting for the completion of an I/O, then the operation must have finished. If a thread is waiting for a lock that was owned by another thread, then the other thread must relinquish ownership of the lock. If a thread waits for a condition, then another thread must signal that the condition may have changed.
Dead thread It dies a natural death because the run() method exits normally. It dies abruptly because an uncaught exception terminates the run method. We cannot restart a dead thread. We cannot call the methods of a dead thread.
Priority of a Thread JRE executes threads based on their priority A CPU can execute only one thread at a time The threads that are ready for execution queue up for processor time. Each thread is given a slice of time after which it goes back into the thread queue. The threads are scheduled using fixed priority scheduling principle. Each thread has a priority that affects its position in the thread queue of the processor A thread with higher-priority runs before threads with low-priority Priority can be set by setpriority(); Syntax: public final void setpriority(int newpriority); Three constants are: 1. MIN_PRIORITY 2. MAX_PRIORITY 3. NORM_PRIORITY Default priority is 5
isalive() and join() methods These are used to determine whether a thread has finished or not First isalive() method is called, which returns true (if thread is still running) or false (otherwise). join() method is used to ensure that a thread has stopped.
Demo:Small modification to main only
class Thread1 implements Runnable { Thread t; String name; int delay; Thread1(String name,int delay) { t = new Thread(this, name); this.name=name; this.delay=delay; t.start(); // Start the thread // This is the entry point for the second thread. public void run()//assign work here { try { for(int i =1; i <=5 ; i++) {System.out.println("Next Number:" + i+ " generated by :"+name); Thread.sleep(delay); catch (InterruptedException e) { System.out.println("Exiting Even child thread.");
public class IsAliveDemo { public static void main(string args[]) { Threads t1=new Threads("First",1000); // create a new thread Threads t2=new Threads("Second",2000); // create a new thread Threads t3=new Threads("Third",3000); // create a new thread System.out.println("Thread One is alive: + t1.t.isalive()); System.out.println("Thread Two is alive: + t2.t.isalive()); System.out.println("Thread Three is alive: + t3.t.isalive()); System.out.println("Main thread exiting."); try { System.out.println("Waiting for threads to finish."); t1.t.join(); t2.t.join(); t3.t.join(); catch (InterruptedException e) {System.out.println("Main thread Interrupted"); System.out.println("Thread One is alive: "+ t1.t.isalive()); System.out.println("Thread Two is alive: "+ t2.t.isalive()); System.out.println("Thread Three is alive: "+ t3.t.isalive());
Output Next Number:1 generated by :First Next Number:4 generated by :Second Next Number:1 generated by :Second Next Number:3 generated by :Third Thread One is alive: true Next Number:5 generated by :Second Thread Two is alive: true Next Number:4 generated by :Third Thread Three is alive: true Exiting child thread:second Main thread exiting. Next Number:5 generated by :Third Waiting for threads to finish. Exiting child thread:third Next Number:1 generated by :Third Thread One is alive: false Next Number:2 generated by :First Thread Two is alive: false Next Number:3 generated by :First Thread Three is alive: false Next Number:2 generated by :Second Next Number:4 generated by :First Next Number:2 generated by :Third Next Number:5 generated by :First Next Number:3 generated by :Second Exiting child thread:first
Need for synchronization When two or more threads need access to a shared resources, they need some way to ensure that the resources will be used by only one thread at a time. The process by which this is achieved is called synchronization.
Background A monitor or semaphore is the key concept behind synchronization. A monitor is an object that is used as a mutually exclusive lock or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads are said to be waiting for the monitor A thread that owns a monitor can re-enter the same monitor. In Java synchronization is achieved by synchronized key word.
Synchronization... By calling sleep( ), the call( ) method allows execution to switch to another thread. This results in the mixed-up output of the three message strings. In this program, nothing exists to stop all three threads from calling the same method, on the same object, at the same time. This is known as a race condition, because the three threads are racing each other to complete the method.
Demo program to print message Problem statement: Design multi thread program in Java to print Message Hello World From Java Each word need to displayed by 4 thread Message to be displayed is single world This could be treated as target block So target block is called be each caller thread Without synchronization output might be: World Hello Java From Java From Java World World Java Hello From
How to fix this problem? To fix the preceding program, you must serialize access to call( ). That is, you must restrict its access to only one thread at a time. To do this, you simply need to precede call( )'s definition with the keyword synchronized, as shown here: class Callme { synchronized void call(string msg) {... This prevents other threads from entering call( ) while another thread is using it.
Inter -thread communication 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.