- Muthayammal E
Transcription
- Muthayammal E
MUTHAYAMMAL COLLEGE OF ARTS & SCIENCE, RASIPURAM. DEPARTMENT OF BCA Staff Name: S.KARTHIK Class: III BCA „A‟ Paper Name: PROGRAMMING IN JAVA Unit: IV Multithreaded Programming A multithreaded program contains two or more task that can run at the same time . For example, one part can display an animation on the screen while another may build the next animation to be displayed. Figure illustrates a Java program with four threads, one main and three others. The main thread is actually the main method module, which is designed to create and start other three threads, namely A, B and C. Main Thread Module Thread A Switching Thread B Thread C Switching Once initiated by the main thread, the threads A,B and C run concurrently and share the resources jointly. ADVANTAGES OF MULTITHREADING Multithreading is used to write very efficient programs. Maximum use of CPU time. The idle time of CPU is reduced. Interprocess communication is faster Multithreading requires less overheads The time required to perform a context switch from one thread to another is less Multithreading reduces the complexity of the large program 1 The resources required for a thread is less than the resources required by a process Creating Threads Threads are implemented in the form of objects that contain a method called run( ). The run( ) method is the heart and soul of any thread. A typical run( ) would appear as follows: public void run( ) { ---- ( Statements for implementing thread ) ---- } The run( ) method should be invoked by an object of the concerned thread. A new thread can be created in two ways. 1. By creating a thread class: Define a class that extends thread class and override its run ( ) method . 2. By converting a class to a thread: Define a class that implements Runnable interface. 1)Extending the thread class Extending the class by java.lang.Thread. It includes the following steps: 1. Declare the class as extending the Thread class 2. Implement the run( ) method that is responsible for executing the sequence of code that the thread will execute. 3. Create a thread object and call the start( ) method to initiate the thread execution. Program: class A extends Thread { public void run( ) { for ( int i=1;i<=3;i++) { System.out.println(“\t From thread A:i=”+i); }} } class B extends Thread{ public void run( ){ for ( int i=1;i<=3;i++) { System.out.println(“\t From thread B:i=”+i); 2 }} } class ThreadTest { public static void main(String[] args) { new A( ).start( ); new B( ).start( ); }} Output From thread A:i=1 From thread A:i=2 From thread B:i=1 From thread B:i=2 From thread A:i=3 Exit from A From thread B:i=3 Exit from B 2)Implementing the Runnable Interface To create thread using the Runnable interface, we must perform the steps listed below: 1. Declare the class as implementing the Runnable interface. 2. Implement the run( ) method. 3. Create a thread by defining an object that is instantiated from this “runnable” class as the target of the thread. 4. Call the thread‟s start( ) method to run the thread. If the direct reference to the thread threadX is not required, then we may use a shortcut as shown below: new Thread( new X( ) ).start( ); Example class X implements Runnable { public void run( ) { for(int i=1;i<3;i++) System.out.println(“\t ThreadX:”+ i); } } class RunnableTest { public static void main(String[] args) 3 { X runnable = new X( ); Thread threadX = new Thread( runnable ); threadX.start( ); } } Output End of main Thread ThreadX:1 ThreadX:2 End of ThreadX Thread Priority In Java, each thread is assigned a priority for running. The threads having same priority are given equal treat by first-come,firstserve basis. Java permits us to set the priority of a thread using the setPriority( ) method as follows: ThreadName.setPriority( int number ); The number is an integer value to which the thread‟s priority is set. MIN_PRIORITY = 1 NORM_PRIORITY=5 MAX_PRIORITY = 10 Whenever multiple threads are ready for execution, the Java system chooses the highest priority thread and executes it. Example class A extends Thread { public void run( ) { System.out.println(“Thread A Started”); for(int i=1;i<=3;i++) System.out.println(i); } } class B extends Thread { public void run( ) { System.out.println(“Thread B Started”); for(int i=1;i<=3;i++) 4 System.out.println(j); }}} class ThreadPriority { public static void main(String args[]) { A threadA = new A( ); B threadB = new B( ); threadB.setPriority( Thread.MAX_PRIORITY); threadA.setPriority(Thread.MIN_PRIORITY); threadA.start( ); threadB.start( ); }} Synchronization When the thread try to use the own data and methods outside themselves on that time one thread may try to send a record from a file while another is still writing to the same file. Depending on the situation, we may get wrong results. Java enables us to overcome this problem using a technique known as synchronization by the keyword synchronized . For example, the method that will read information from a file and the method that will update the same file may be declared as synchronized. Example synchronized void update( ) { ---- // code here is synchronized ---} ----} Whenever a thread has completed its work by using synchronized method, it will hand over the monitor to the next thread that is ready to use the same resource. An interesting situation may occur when two or more threads are waiting to gain control of a resource. This result in what is known as deadlock. LIFE CYCLE OF THE THREAD The following states can occur during the life time of a thread. Each thread is always in one of the five states. 1. Newborn state 2. Runnable state 5 3. Running state 4. Blocked state 5. Dead state wait ( ) Blocked suspend ( ) sleep( ) notify ( ) resume ( ) Newborn Runnable Running start( ) yield ( ) stop ( ) stop( ) stop ( ) Dead NEWBORN STATE A thread is in newborn state immediately after it is created. The thread object has created the new state . It requires the start( ) method to start it. Newborn next stop Runnable State Dead State RUNNABLE STATE 6 The runnable state means that a thread is ready to run and is awaiting for the control of the processor. That is, the thread has joined the queue of threads that are waiting for execution. yield ( ) Runnable Threads Running Thread RUNNING STATE A thread is said to be in running state, when it is executing a set of instructions. The run( ) method contains the set of instructionThe run ( ) method is called automatically after start ( ) method. A running state continues until any one of the following occurs Suspend ( ) running runnable suspended wait 7 running runnable suspended sleep (t) running runnable suspended After the completion of the execution When the method sleep ( ) is called. When the method wait ( ) is called. When the method suspend ( ) is called. BLOCKED STATE A thread is in blocked state, if it is being prevented from the runnable state or running state. This happens when thread is suspended. Sleeping, or waiting in order to satisfy certain requirements. A blocked state is considered as “not runnable” but not dead DEAD STATE A thread is Dead when it finishs its execution (natural death) or is stopped (killed) by another thread (premature death) Example class A extends Thread { public void run( ) { for(int i=1; i< 3;i++) { if (i == 1 ) yield( ); System.out.println(i);} }} 8 class B extends Thread { public void run( ) { for(int j=1 ;j<=5;j++) { System.out.println(j); if (j==3 ) stop( ); }}} class C extends Thread { public void run( ) { for(int k=1; k<=3;k++) { System.out.println(k); if (k = = 1 ) try{ sleep(1000); } catch( Exception e) {} }} }class ThreadMethods { public static void main(String[] args) { A threadA =new threadA( ); B threadB =new threadB( ); C threadC =new threadC( ); ThreadA.start( ); ThreadB.start( ); ThreadC.start( ); } } 9