By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology
UNIT-2 Interface,Multithreading,Exception Handling Interfaces : defining an interface, implementing & applying interfaces, variables in interfaces, extending interfaces. Multithreading :Basic idea of multithreaded programming; The lifecycle of a thread; Creating thread with the thread class and runnable interface; Thread synchronization; Thread scheduling; Producer-consumer relationship; Daemon thread, Selfish threads; Basic idea of exception handling; The try, catch and throw; throws Constructor and finalizers in exception handling; 2
Multithreading :Basic idea of multithreaded programming; 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. 3
The lifecycle of a thread 4
1. New state? After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 2. Runnable (Ready-to-run) state? A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 3. Running state? A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 4. Dead state? A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. 5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread. 5
Different states implementing Multiple-Threads are: Sleeping? On this state, the thread is still alive but it is not runnable, it might be return to runnable state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time. You can use the method sleep( ) to stop the running state of a thread. static void sleep(long millisecond) throws InterruptedException 6
Waiting for Notification? A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread. final void wait(long timeout) throws InterruptedException final void wait(long timeout, int nanos) throws InterruptedException final void wait() throws InterruptedException Blocked on I/O? The thread waits for completion of blocking operation. A thread can enter on this state because of waiting I/O resource. In that case the thread sends back to runnable state after availability of resources. Blocked for joint completion? The thread can come on this state because of waiting the completion of another thread. Blocked for lock acquisition? The thread can come on this state because of waiting to acquire the lock of an object. 7
Creating thread with the thread class and runnable interface There are two ways of implementing threading in Java 1. By extending java.lang.thread class, or 2. By implementing java.lang.runnable interface. 1. Extending the Thread class: 1. In this method one normal class extends the inbuilt class thread and override its run() method with the code required by that particular thread. 2. Here we are going to extend class java.lang.thread. so we can access all the methods of thread class. 3. Create one class which extends the thread class. 4. Override the run method and put lines of code inside thread method that will be perform by thread. 5. Create an object of class which we created with extending the thread class and call the start() method to execute the thread. 8
Class MyThread extends Thread.... So now we have one thread named MyThread. Implementing the run() method Public void run() // Thread code here Starting new Thread MyThread ath = new MyThread(); // it instantiates a new object of class MyThread ath.start(); // invokes run() method 9
class A extends Thread public void run() System.out.println("Thread A"); for(int i=1;i<=50;i++) System.out.println("From thread A i = " + i); System.out.println("Exit from A"); class B extends Thread public void run() System.out.println("Thread B"); for(int i=1;i<=50;i++) System.out.println("From thread B i = " + i); System.out.println("Exit from B"); public class Thread_Class public static void main(string[] args) new A().start(); //creating A class thread object and calling run method new B().start(); //creating B class thread object and calling run method System.out.println("End of main thread"); 10
2. Implementing the Runnable interface: 1. In this method we have one interface named runnable and we implements this interface for implement a thread. 2. Create one class which implements runnable interface. 3. Override the run() method and put some line of code for that particular thread. 4. Now create an object of inbuilt thread class and create an object of class that implements runnable interface. 5. Give the reference of object to thread object by passing an argument (argument must be the object of class which implements the runnable interface) while creating a thread object. 6. Call the start() method to run the thread. 11
public class Thread_Interface public static void main(string[] args) X x1 = new X(); //class object Thread xthread = new Thread(x1); //creating thread object and giving reference of class object to thread object xthread.start(); System.out.println("End of main Thread"); Output : class X implements Runnable public void run() System.out.println("Inside X thread"); for(int i=1;i<=10;i++) System.out.println("From xthread i = " +i); System.out.println("Exit from X"); End of main Thread Inside X thread From xthread i = 1 From xthread i = 2 From xthread i = 3 From xthread i = 4 From xthread i = 5 From xthread i = 6 From xthread i = 7 From xthread i = 8 From xthread i = 9 From xthread i = 10 Exit from X 12
Java thread scheduling & thread Priority: Features : 1.The JVM schedules using a preemptive, priority based scheduling algorithm. 2.All Java threads have a priority and the thread with he highest priority is scheduled to run by the JVM. 3.In case two threads have the same priority a FIFO ordering is followed. 4.In Java program, you create threads but they are not executed by Java alone. Java takes the help of the underlying OS to execute them. 5. To allocate microprocessor time and to supervise all the threads' execution, the OS comes with Thread Scheduler. 6. The entire responsibility of maintaining the sequence of execution of threads, where which thread should be given first preference than the other, lies with the thread scheduler. 7. The scheduling depends on the algorithm of the scheduler. Many types of algorithms exist like preemptive and time slicing with round robin etc. 13
Java thread scheduling & thread Priority: 1. Each java thread has its own priority which decides the order of thread to be schedule. 2. The threads of equal priority will be given same treatment by java scheduler. And they will follow the FCFS (First Come First Serve) algorithm. 3. User can also set the priority of thread by using the setpriority() method as follow: ThreadName.setPriority(int Number); Here the number is integer value between 1 to 10, Here 1 is minimum priority 10 is maximum priority. The Thread class defines few priority constants: MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 In any Thread the default priority is NORM_PRIORITY Whenever more than one threads are ready to run java system select the highest priority thread and execute it If another thread of higher priority comes the running thread will be preempted by the incoming thread and current thread will move to runnable state. 14
class A extends Thread public void run() System.out.println("ThreadA strated"); for(int i = 1; i<=5; i++) System.out.println("\t From ThreadA i = " +i); System.out.println("Exit from A"); public class Thread_Priority public static void main(string[] args) A threada = new A(); B threadb = new B(); threada.setpriority(thread.min_priority); threadb.setpriority(threada.getpriority()+3); System.out.println("Start Thread A"); threada.start(); class B extends Thread public void run() System.out.println("ThreadB strated"); for(int j = 1; j<=5; j++) System.out.println("\t From ThreadB j = " +j); System.out.println("Exit from B"); System.out.println("Start Thread B"); threadb.start(); System.out.println("End of main Thread"); Output: Start Thread A Start Thread B End of main Thread ThreadB strated From ThreadB j = 1 From ThreadB j = 2 From ThreadB j = 3 From ThreadB j = 4 From ThreadB j = 5 Exit from B ThreadA strated From ThreadA i = 1 From ThreadA i = 2 From ThreadA i = 3 From ThreadA i = 4 From ThreadA i = 5 Exit from A 15
Thread synchronization When 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. The synchronized keyword in Java creates a block of code referred to as a critical section. Every Java object with a critical section of code gets a lock associated with the object. To enter a critical section, a thread needs to obtain the corresponding object's lock. This is the general form of the synchronized statement: synchronized(object) // statements to be synchronized 16
Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object's monitor. 17
Java - Exceptions Handling 18
An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory. 19
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions: Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. 20
try //Protected code catch(exceptionname e1) //Catch block import java.io.*; public class ExcepTest public static void main(string args[]) try int a[] = new int[2]; System.out.println("Access element three :" + a[3]); catch(arrayindexoutofboundsexception e) System.out.println("Exception thrown :" + e); System.out.println("Out of the block"); 21
Multiple catch Blocks: try //Protected code catch(exceptiontype1 e1) //Catch block catch(exceptiontype2 e2) //Catch block catch(exceptiontype3 e3) //Catch block 22
The throws/throw Keywords: If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. 23
The finally Keyword The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. try //Protected code catch(exceptiontype1 e1) //Catch block catch(exceptiontype2 e2) //Catch block catch(exceptiontype3 e3) //Catch block finally //The finally block always executes. 24
public class ExcepTest public static void main(string args[]) int a[] = new int[2]; try System.out.println("Access element three :" + a[3]); catch(arrayindexoutofboundsexception e) System.out.println("Exception thrown :" + e); finally a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); Exception thrown :java.lang.arrayindexoutofboundsexception: 3 First element value: 6 The finally statement is executed 25
class MyException extends Exception public MyException(String msg) super(msg); public class MyTest static int divide(int first,int second) throws MyException if(second==0) throw new MyException("can't be divided by zero"); return first/second; public static void main(string[] args) try System.out.println(divide(4,0)); catch (MyException exc) exc.printstacktrace(); 26
27