Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Multi Threading

The document discusses multithreading in Java. It defines key terms like thread, multithreading, and concurrency. It describes how to create threads by extending the Thread class and implementing the Runnable interface. It also explains common thread methods like sleep, yield, join and their usage.

Uploaded by

Akshay Raul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Multi Threading

The document discusses multithreading in Java. It defines key terms like thread, multithreading, and concurrency. It describes how to create threads by extending the Thread class and implementing the Runnable interface. It also explains common thread methods like sleep, yield, join and their usage.

Uploaded by

Akshay Raul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Multithreading in Java

❖ Key Definition:
Thread: A thread is similar to program that has a single flow of control.

Multithreading: A program which contains multiple flow of control is known as


multithreaded program and the process is known as Multithreading.

Concurrency: The ability of the language to support Multithreads is referred to as Concurrency.

Synchronization: When there threads are sharing the resources, they compete for the resources which may
lead to serious problems like deadlock. For eg: 2 threads try to access same file one thread reads from it & the
other wants to write into the file. This may result in strange & unexpected output. To deal with such situation
threads sharing the common resources needs to be synchronized so that the threads do not interfere with each
other. The process is known as Synchronization.

CREATING THREADS
To create threads in Java program we extend library class called Thread of java.lang package. The steps of
extending Thread class are:
(1) Declare a class and extend Thread class.
(2) Create thread using run() method
(3) Execute threads using start() method.

Example 5.1:
class A extends Thread OUTPUT:
{ public void run()
{ for(int i=0;i<5;i++) starting main thread
System.out.println(“from Thread A : i=”+i); starting thread A
} starting thread B
System.out.println(“Exit from Thread A”); starting thread C
} from Thread A : i= 0
class B extends Thread from Thread A : i= 1
{ public void run() from Thread A : i= 2
{ for(int i=0;i<5;i++) from Thread B : i= 0
System.out.println(“from Thread B : i=”+i); Exit from main thread
} from Thread B : i= 1
System.out.println(“Exit from Thread B”); from Thread C : i= 0
} from Thread A : i= 3
class C extends Thread from Thread A : i= 4
{ public void run() Exit from Thread A
{ for(int i=0;i<5;i++) from Thread B : i= 2
System.out.println(“from Thread C : i=”+i); from Thread B : i= 3
} from Thread B : i= 4
System.out.println(“Exit from Thread C”); Exit from Thread B
} from Thread C: i= 1
class test from Thread C : i= 2
{ public static void main(String s[]) from Thread C : i= 3
{ System.out.println(“starting main thread”); from Thread C : i= 4
A ta =new A(); Exit from Thread C
B tb= new B(); Note: Output may vary with different
C tc= new C(); executions
System.out.println(“starting thread A”);
ta.start();
System.out.println(“starting thread B”);
tb.start();
System.out.println(“starting thread C”);
tc.start();
System.out.println(“Exit from main thread ”);
}
}

Page 1
To create threads in Java program we implement Runnable interface. Runnable interface declares run()
method to implement thread. The steps of implementing Runnable interface are:
(1) Declare a class and implement Runnable interface.
(2) Create Thread using run() method.
(3) Create Thread object from Thread class and pass the object of Runnable interface to Thread class
constructor to access start() method of Thread class.
(4) Execute threads using start().

Example 5.2:
class A implements Runnable OUTPUT:

{ public void run() value of i in class A: 0 value of i


in class B: 0 value of i in class A:
{ for(int i=0;i<5;i++) 1 value of i in class B: 1 value of i
in class A: 2 value of i in class B:
System.out.println(“Value of i in class A:”+i); 2 value of i in class A: 3 value of
i in class B: 3 value of i in class A:
}
4 value of i in class B: 4
System.out.println(“End of class A”);
End of class A
}
End of class B
class B implements Runnable

{ public void run()

{ for(int i=0;i<5;i++)

System.out.println(“Value of i in class B:”+i);

System.out.println(“End of class B”);

class test

{ public static void main(String s[])

{ A a1 =new A();

B b1= new B();

Thread t1=new Thread(a1);

Thread t2=new Thread(b1);

t1.start();

t2.start();

Page 2
THREAD METHODS
In Java Thread class provides following methods:

➢ stop() method: stops running thread and causes it to move to dead state.

Syntax:- Threadobject.stop();

➢ sleep() method: blocks execution of thread for specified time in milliseconds. The method generates
exceptions hence written in try catch block.

Syntax:- sleep(time in ms);

➢ suspend() method: blocks execution until further order. Thus resume() method is invoked for
executing it again.

Syntax:-

➢ wait() method: blocks execution until certain condition occurs. notify() method is invoked for executing
it again.

Syntax:-

➢ yield() method: gives control to another thread before its run() comes.

Syntax:-

Example 5.3:
Class A extends Thread OUTPUT:
{ public void run()
{ for(int i=0;i<=2;i++) value of i in class A: 0 value of i in
{ if(i==0) yield(); class A: 1 value of i in class B: 0
System.out.println(“value of i in class A: ”+i); value of i in class A: 2 End of class A
} value of i in class B: 1 value of i in
System.out.println(“End of class A”); class B: 2 End of class B
}
}
Class B extends Thread
{ public void run()
{ for(int i=0;i<=2;i++)
{ if(i==1)
try
{ sleep(1000);
} catch(Exception e) { }
System.out.println(“value of i in class B: ”+i);
}
System.out.println(“End of class A”);
}
}
class thread3
{ public static void main(String args[])
{ A a1=new A();
B b1=new B();
a1.start();
b1.start();
}
}

Page 3
➢ isAlive() method: checks whether thread is running or not and returns true if running else returns
false.

Syntax:- Boolean isAlive();

➢ join() method: waits for thread to finish. It ensures that main() thread is last to stop.

Syntax:-

Example 5.4:
Class A extends Thread OUTPUT:
{ public void run()
{ for(int i=0;i<=4;i++) value of i in class A: 0 For
System.out.println(“value of i in class A: ”+i); thread A: true value of i in class
System.out.println(“End of class A”); A: 1 For thread B: false value of
} i in class A: 2 Thread A waiting
} to finish value of i
Class B extends Thread in class B: 0 value of i in class A:
{ public void run() 3 value of i in class B: 1 value of
{ for(int i=0;i<=4;i++) i in class A: 4 value of i in class
System.out.println(“value of i in class B: ”+i); B: 2 End of class A
System.out.println(“End of class A”); value of i in class B: 3 Thread B
} waiting to finish
} value of i in class B: 4 End of
class thread21 class B
{ public static void main(String args[]) End main thread last confirmed
{ A a1=new A();
a1.start();
System.out.println(“For thread A:
"+a1.isAlive());
B b1=new B();
System.out.println(“For thread B: "+b1.isAlive());
b1.start();
try
{ System.out.println(“Thread A waiting to
finish: ");
a1.join();
System.out.println(“Thread B waiting to
finish: ");
b1.join();
} catch(InterruptedException e){ }
System.out.println(“End main thread last confirmed");
}
}

➢ setPriority() method: sets the priorities of threads for execution.

Syntax:- threadobject.setPriority(intNumber);

Thread class defines three priorities:

MIN_PRIORITY=1 NORM_PRIORITY=5 MAX_PRIORITY=10

Page 4
Example 5.5:
Class A extends Thread OUTPUT:
{ public void run()
{ for(int i=0;i<=4;i++) value of i in class B: 0
{ if(i==0) yield(); value of i in class C: 0
System.out.println(“value of i in class A: ”+i); value of i in class A: 0
} value of i in class B: 1
System.out.println(“End of class A”); value of i in class C: 1
} value of i in class A: 1
} value of i in class B: 2
Class B extends Thread value of i in class C: 2
{ public void run() value of i in class A: 2
{ for(int i=0;i<=4;i++) value of i in class B: 3
System.out.println(“value of i in class B: ”+i); value of i in class C: 3
System.out.println(“End of class B”); value of i in class A: 3
} value of i in class B: 4
} value of i in class C: 4
Class C extends Thread value of i in class A: 4
{ public void run() End of class C
{ for(int i=0;i<=4;i++) End of class B
System.out.println(“value of i in class C: ”+i); End of class A
System.out.println(“End of class C”);
}
}
class thread11
{ public static void main(String args[])
{ A a1=new A();
B b1=new B();
C c1=new C();
a1.setPriority(1);
b1.setPriority(5);
c1.setPriority(10);
a1.start();
b1.start();
c1.start();
}
}

Page 5
LIFECYCLE OF THREAD

Active Thread
Suspend
Idle Thread
New Thread
Sleep or Runnable
New Born start
Runnable Running wait Blocked

resume

yield notify

stop stop
stop
Dead

Killed Thread

➢ NEW BORN STATE:- When a thread object is created, thread is born and is not yet scheduled for
running. Attempt to use any other method except start() and stop() cause an exception to be thrown.
➢ RUNNABLE STATE:- Thread is ready for execution and waiting for availability from processor.
Thread are given time slots in First come first serve manner.
➢ RUNNING STATE:- Processor has given time to thread for execution. Thread runs until it
relinquishes control on its own or is preempted by higher priority thread.
➢ BLOCKED STATE:- When a thread prevented from entering into runnable and subsequently
running state. The thread is not dead and hence fully qualified to run again.
➢ DEAD STATE:- A running thread comes to this state when it has stopped executing its run() method
or by sending stop() message to it at any stage.

THREAD SYNCHRONIZATION

When threads try to use data and methods outside them, they can compete for same resources (data and
method) and may lead to serious problems (Deadlock). Java overcomes this problem using technique
synchronization via synchronized keyword. Thus synchronization acquires object locks between interleaved
executions of multiple threads and hence changes made by one thread will be guaranteed to reflect to another
thread.

Example 5.6:
class Name OUTPUT:
{ synchronized void call(String msg)
{ System.out.print(“[“+msg); [Parvez]

Page 6
try [Vaghela]
{ Thread.sleep(500); /*if I remove synchronized keyword
} catch(InterruptedException e){ } from call method following output
System.out.print(“]“); produced*/
} [Parvez[Vaghela]
} ]
class FullName implements Runnable
{ String msg;
Name target;
Thread t;
public FullName(Name targ,String s)
{ target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{ target.call(msg);
}
}
class Syn
{ public static void main(String args[])
{ Name target=new Name();
FullName first=new FullName(target,”Parvez”);
FullName last=new FullName(target,” Vaghela”);
try
{ first.t.join();
last.t.join();
} catch(InterruptedException e){ }
}
}
❖ References:
1) Programming with JAVA A Primer, 3rd Edition, E Balagurusamy
2) The Complete Reference JAVA, Seventh Edition, Herbert Schildt
3) http://www.tutorialspoint.com

Question Bank
OBJECTIVE QUESTIONS
1. Which keyword can protect a class in a package from accessibility by classes outside
package?
a. private b. protected c. final d. don’t use keyword
2. We would like to make a member of a class visible in all subclasses regardless of what
package they are in. Which one of the following keywords would achieve this?
a. private b. protected c. public d. private protected
3. The use of protected keyword to a member in a class will restrict its visibility as
follows:
a. visible only in the class and its subclass in the same package b. visible only in same
package c. visible in all classes same package and subclasses in other packages d.
visible only in the class where it is declared
4. A package is a collection of
a) classes b) interfaces c) editing tools d) classes and interfaces
5. When we implement runnable interface, we must define the method
a. start() b. init() c. run() d. runnable() e. resume() f. main()
6. The methods wait() and notify() are defined in
a. java.lang.String b. java.lang.Runnable c. java.lang.Object d.
java.lang.Thread e. java.lang.ThreadGroup
Page 7
7. Which of the following is not a state of thread?
a. New b. Execute c. Runnable d. Running
8. Which of the following package is imported automatically in java program?
a. java.awt b. java.net c. java.lang d. java.applet
9. A ….. member of a class can be accessed from anywhere in a java application.
a. public b. protected c. private d. defult
10. Which of the following method is called when object is garbage collected
a) run() b) finalize() c) toString() d) notify()
Answers:
1) d 2) d 3) c 4) d 5) c 6) c 7) b 8) c 9) a 10) b

SUBJECTIVE QUESTIONS
What is Thread? How is it created?
What is the difference between multiprocessing and multithreading?
Write a program to print 1A2B3C4D5E6F7G8H9I10J using two child
threads.
Explain methods of class thread?
Write a program to illustrate use of isAlive() and Join() and sleep()
methods.
Describe complete lifecycle of a thread.
What is synchronization? When do we use it?

With help of a suitable program explain multithreaded programming in


terms of following:
(i) create threads, extend thread class
(ii) stop and block a thread
(iii) lifecycle of a thread
Explain lifecycle of thread and five methods of Thread class.
Write a program to create multiple threads.
Write short note on
synchronization.
Write a program to illustrate use of isAlive() and join() and sleep()
method. Create three classes A,B and C. Create another class “IsAliveJoin” to invoke
isAlive() and join() methods for these 3 child threads.
Write a program to print */*/*/*/*/*/*/ using two child thread. (Hint : One thread is
responsible to print * another is for /).

Exception
 Users have high expectations for the code we produce.
 Users will use our programs in unexpected ways.
 Due to design errors or coding errors, our programs may fail in unexpected ways during execution

Page 8
 It is our responsibility to produce quality code that does not fail unexpectedly.
 Consequently, we must design error handling into our programs.
Errors and Error Handling
 An Error is any unexpected result obtained from a program during execution.
 Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program
termination.
 Errors should be handled by the programmer, to prevent them from reaching the user.
Exception-Handling Fundamentals
 A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a
piece of code.
 When an exceptional condition arises, an object representing that exception is created and thrown in the
method that caused the error.
 Either way, at some point, the exception is caught and processed.
 Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
 Program statements that you want to monitor for exceptions are contained within a try block.
 If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch)
and handle it in some rational manner.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be specified as such by a throws clause.
 Any code that absolutely must be executed before a method returns is put in a finally block.
The program rarely runs successfully in the first attempt. It is common to make mistakes
while developing as well as typing a program. A mistake might lead to an error causing
the program to produce unexpected results.
Why use Exception handling:
An error may produce an incorrect output or may terminate the execution of the program
abruptly or may even cause a system to crash. It is therefore important to detect and
manage properly all possible error conditions in a program so that the program will not
crash down during execution.
Let us start our study with a simple example:
class Error
{
public static void main(String args[])
{
int a = 10;
int b= 5;
int c=5;
int x=a/(b-c);
System.out.println(x);
int y= a/(b+c);
System.out.println(y);
}
}
/*C:\Java\jdk1.5.0_04\bin>javac Error.java
C:\Java\jdk1.5.0_04\bin>java Error
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Error.main(Error.java:8)*/
At run time the divide by zero message is displayed and the program stops.
Errors may be classified into two categories as Compile time and Run time errors.

Compile Time Errors: All syntax errors will be detected and displayed by the Java
compiler and therefore these errors are called as compile time errors. Whenever the
compiler displays an error it will create the .class file. It is therefore necessary that we fix
the errors before we successfully compile and run the program. The most common
problems are:
• Missing semicolons
• Missing brackets in classes and methods
• Misspelling of identifiers and keywords
• Missing double quotes in strings
• Use of undeclared variables
• Incompatible type in assignments / initialization
• Bad reference to objects

Page 9
Run Time errors: A program may compile successfully creating a .class file but may not
run properly. Such programs may produce wrong results due to wrong logic or may
terminate such as stack overflow. Most common run time errors are:
• Dividing an integer by zero.
• Accessing an element that is out of bound of in an array.
• Trying to store a value into an array of an incompatible class or type.
• Passing a parameter that is not in a valid range or value for a method
• Attempting to use a negative size for an array
• Use a null object reference as a legitimate object reference to access a method or a
variable
• Converting an invalid string into a number
When such errors are encountered, Java typically generates an error message and aborts
the program.
14.2 Exceptions:
An exception is a condition that is caused by a run time error in the program. When the
Java interpreter encounters an error such as dividing an integer by zero, it creates an
exception object and throws it.
If the exception object is not caught and handled properly, the interpreter will
display an error message as shown in the output of program and will terminate the
program. If we want the program to continue with the execution of the remaining code,
then we should try to catch the exception object thrown by the error condition and then
display an appropriate message for taking corrective actions. This is called as exception
handling.
The purpose of exception handling mechanism is to provide a means to detect and
report an “exceptional circumstance” so that appropriate action can be taken. The
mechanism suggests incorporation of a separate error handling code that performs the
following tasks:
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred (Throws the exception)
3. Receive the error information (Catch the exception)
4. Take the corrective actions (Handle the exception)

The error handling code basically consists of two segments one to detect errors and to throw exceptions and other to
catch exceptions and to take appropriate actions. While writing programs we must always be on the look out for places
in the program where an exception could be generated. Some common exceptions that we must watch out for
catching are listed in the table:

Exception Types

Page 10
 All exception types are subclasses of the built-in class Throwable.
 Throwable are two subclasses that partition exceptions into two distinct branches.
 One branch is headed by Exception. This class is used for exceptional conditions that user programs
should catch.
Exception type Cause of Exception
ArithmeticException Caused by Math errors such as divide by zero
ArrayIndexOutOfBoundExce Caused by error indexes
ArrayStoreException Caused when a program tries to store wrong data in
array
FileNotFoundException Caused by an attempt to access a nonexistent file
IOException Caused by general I/O failures such as inability to read
from a file
NullPointerException Caused by referencing a null object
NumberFormatException Caused when conversion between strings and number
fails
OutOfMemoryException Caused when there is not enough memory to allocate a
new object
SecurityException Caused when an applet tries to perform action not
allowed by browser’s security
StackOverflowException Caused when the system runs out of stack space
StringIndexOutOfBoundsException Caused when a program attempts to access a
nonexistent character position in a string

This is the general form of an exception-handling block:


try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}

Java uses a keyword try to prefer a block of code that is likely to cause an error condition and “throw” an exception. A
catch block defined by the keyword catch “catches” the exception “thrown” by the try block and handles it
appropriately. The catch block is added after the try block.

14.2.1 Arithmetic Exception:

class Error
{

Page 11
public static void main(String args[])
{
int a=10,b=5,c=5,x,y;
try
{
x=a/(b-c);
} catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
y=a/(b+c);
System.out.println("y = " +y);
}
}
/*Divide by zero
y = 1*/
14.2.2 Catching Invalid Command line arguments:
class ClineInput
{
public static void main(String args[])
{ int invalid=0,count=0,num;
for(int i=0;i<args.length;i++)
{
try
{
num=Integer.parseInt(args[i]);
}
catch(NumberFormatException e)
{
invalid++;
System.out.println("Invalid arguments :"+args[i]);
continue;
} count++;
}
System.out.println("Valid arguments :"+count);
System.out.println("InValid arguments :"+invalid);
}}
/*C:\Java\jdk1.5.0_04\bin>javac ClineInput.java
C:\Java\jdk1.5.0_04\bin>java ClineInput Java 10 17.5 18 you
Invalid arguments :Java
Invalid arguments :17.5
Invalid arguments :you
Valid arguments :2
InValid arguments :3*/

14.2.3 Catch multiple exceptions


It is possible to have more than one catch statement in the catch block as illustrated below:
try
{
statement;
} catch(ExceptionType1 e)
{statement;}
catch(ExceptionType2 e)
{statement;}
catch(ExceptionType3 e)
{statement;}
When an exception in a try block is generated, Java treats the multiple catch statements like cases in switch statement.
The first statement whose parameter matches with the exception object will be executed and the remaining statements
will be skipped.
class Error
{

Page 12
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x = a[2]/b-a[1];
} catch(ArithmeticException e)
{
System.out.println("Division byb zero");
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
} catch(ArrayStoreException e)
{
System.out.println("Wrong Datatype");
} int y=a[1]/a[0];
System.out.println("y= "+y);
}}
/*C:\Java\jdk1.5.0_04\bin>javac Error.java
C:\Java\jdk1.5.0_04\bin>java Error
Array Index Error
y= 2*/
14.2.4 The finally keyword
Java supports another statement known as finally statement that can be used to handle an
exception that is not caught by any of the previous catch statements. finally block can be
used to handle any exception generated within a try block. It may be added immediately
after the try block or after the last catch block shown as follows:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
14.2.5 Throwing our Exception:
There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as
follows: throw new Throwable_subclass
example:
throw new ArithmeticException( ) ;
throw new NumberFormatException( ) ;

Page 13

You might also like