Java Unit 4
Java Unit 4
Java Unit 4
Multithreading
But we use multithreading than multiprocessing because threads share a common memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
1
o Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
2
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)z
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
3
has not selected it to be the running thread.
4
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
6
on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing
thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
Starting a thread:
7
start() method of Thread class is used to start a newly created thread. It performs
8
following tasks:
10
If you are not extending the Thread class,your class object would not be treated as a
thread object.So you need to explicitely create Thread class object.We are passing the
object of your class that implements Runnable so that your class run() method may
execute.
12
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Joining threads
Sometimes one thread needs to know when another thread is ending. In
java, isAlive() and join() are two different methods to check whether a thread has finished
its execution.
The isAlive() methods return true if the thread upon which it is called is still running
otherwise it return false.
final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until the
thread on which it is called terminates.
final void join() throws InterruptedException
Using join() method, we tell our thread to wait until the specifid thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time
for which you want to wait for the specified thread to terminate.
final void join(long milliseconds) throws InterruptedException
System.out.println("r1 ");
13
try{ Thread.sleep(5
00);
}catch(InterruptedException ie){}
System.out.println("r2 ");
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
Output
r1
true
true
r1
r2
r2
14
Example of thread without join() method
public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try{
Thread.sleep(500);
}catch(InterruptedException ie){}
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new
MyThread(); MyThread
t2=new MyThread(); t1.start();
t2.start();
}
}
Output
r1
r1
r2
r2
In this above program two thread t1 and t2 are created. t1 starts first and after printing
15
"r1" on console thread t1 goes to sleep for 500 mls.At the same time Thread t2 will start its
16
process and print "r1" on console and then goes into sleep for 500 mls. Thread t1 will wake
up from sleep and print "r2" on console similarly thread t2 will wake up from sleep and
print "r2" on console. So you will get output like r1 r1 r2 r2
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread(); MyThread t2=new MyThread();
t1.start();
try{
t1.join();
//Waiting for t1 to finish
}catch(InterruptedException ie){}
t2.start();
}
17
}
Output
r1
r2
r1
r2
In this above program join() method on thread t1 ensure that t1 finishes it process before
thread t2 starts.
If in the above program, we specify time while using join() with m1, then m1 will execute
for that time, and thenm2 and m3 will join it.
m1.join(1500);
Doing so, initially m1 will execute for 1.5 seconds, after which m2 and m3 will join it.
In the last chapter we have seen the ways of naming thread in java. In this chapter we will
be learning the different priorities that a thread can have.
1. Logically we can say that threads run simultaneously but practically its not true,
only one Thread can run at a time in such a ways that user feels that concurrent
environment.
2. Fixed priority scheduling algorithm is used to select one thread for execution based
on priority.
package com.c4learn.thread;
18
public class ThreadPriority extends Thread {
t1.start();
t2.start();
}
}
Output :
5
5
Each thread has normal priority at the time of creation. We can change or modify the
thread priority in the following example 2.
package com.c4learn.thread;
t1.setPriority(Thread.MAX_PRIORITY);
t0.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t0.start();
t1.start();
t2.start();
}
}
Output :
4. At a time many thread can be ready for execution but the thread with highest
priority is selected for execution
5. Thread have default priority equal to 5.
MIN_PRIORITY 1
MAX_PRIORITY 10
NORM_PRIORITY 5
21
4. Thread Synchronization is achieved through keyword synchronized.
22
Typesof Synchronization :
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
23
Why use Synchronization
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
24
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent access
to an object's fields has to acquire the object's lock before accessing them, and then release
the lock when it's done with them.
1. Class Table{
2.
3. void printTable(int n){//method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25
25. Table t;
26. MyThread2(Table t){
26
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. class TestSynchronization1{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }
Output: 5
100
10
200
15
300
20
400
25
500
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
28
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }
29
Output: 5
10
15
20
25
100
30
200
300
400
500
In this program, we have created the two threads by annonymous class, so less coding is
required.
31
31. }
32. }
32
Output: 5
10
15
20
25
100
200
300
400
500
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
33
1. class Table{
2.
34
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. class MyThread1 extends Thread{
16. Table t;
17. MyThread1(Table t){
18. this.t=t;
19. }
20. public void run(){
21. t.printTable(5);
22. }
23.
24. }
25. class MyThread2 extends Thread{
26. Table t;
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
32. }
33. }
34.
35. public class TestSynchronizedBlock1{
36. public static void main(String args[]){
37. Table obj = new Table();//only one object
38. MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40. t1.start();
41. t2.start();
42. }
43. }
35
Output:5
10
15
20
36
25
100
200
300
400
500
1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. public class TestSynchronizedBlock2{
16. public static void main(String args[]){
17. final Table obj = new Table();//only one object
18.
19. Thread t1=new Thread(){
20. public void run(){
21. obj.printTable(5);
22. }
23. };
24. Thread t2=new Thread(){
25. public void run(){
26. obj.printTable(100);
27. }
28. };
29.
30. t1.start();
37
31. t2.start();
32. }
38
33. }
Output:5
10
15
20
25
100
200
300
400
500
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In
case of synchronized method and synchronized block there cannot be interference
between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have
a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1
acquires another lock and t3 acquires another lock.I want no interference between t1 and
39
t3 or t2 and t4.Static synchronization solves this problem.
40
Example of static synchronization
In this example we are applying synchronized keyword on the static method to perform
static synchronization.
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. public void run(){
15. Table.printTable(1);
16. }
17. }
18.
19. class MyThread2 extends Thread{
20. public void run(){
21. Table.printTable(10);
22. }
23. }
24.
25. class MyThread3 extends Thread{
26. public void run(){
27. Table.printTable(100);
28. }
29. }
30. class MyThread4 extends Thread{
31. public void run(){
32. Table.printTable(1000);
33. }
34. }
35.
36. public class TestSynchronization4{
37. public static void main(String t[]){
38. MyThread1 t1=new MyThread1();
39. MyThread2 t2=new MyThread2();
41
40. MyThread3 t3=new MyThread3();
42
41. MyThread4 t4=new MyThread4();
42. t1.start();
43. t2.start();
44. t3.start();
45. t4.start();
46. }
47. }
43
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
44
2000
3000
4000
5000
6000
7000
8000
9000
10000
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. public class TestSynchronization5 {
14. public static void main(String[] args) {
15.
16. Thread t1=new Thread(){
17. public void run(){
18. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
45
27.
46
28. Thread t3=new Thread(){
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
45. }
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
47
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
The block synchronizes on the lock of the object denoted by the reference .class name
.class. A static synchronized method printTable(int n) in class Table is equivalent to the
following declaration:
48
until resume() method is called on it. These methods are deprecated, as when not used
49
with precautions, the thread locks, if held, are kept in inconsistent state or may lead to
deadlocks.
Note: You must have noticed, in the earlier sleep() method, that the thread in blocked state
retains all its state. That is, attribute values remains unchanged by the time it comes into
runnable state.
Suspend Resume Thread: Program explaining the usage of suspend() and resume()
methods
2{
4 {
7 srd1.setName("First");
8 srd2.setName("Second");
9 srd1.start();
10 srd2.start();
11 try
12 {
13 Thread.sleep( 1000 );
14 srd1.suspend();
16 Thread.sleep( 1000 );
17 srd1.resume();
50
19
20 Thread.sleep(1000);
21 srd2.suspend();
22 System.out.println("Suspending thread Second");
23 Thread.sleep(1000);
24 srd2.resume();
25 System.out.println("Resuming thread Second");
26 }
27 catch(InterruptedException e)
28 {
29 e.printStackTrace();
30 }
31 }
33 {
34 try
35 {
37 {
38 Thread.sleep(500);
40 }
41 }
42 catch(InterruptedException e)
51
43 {
44 e.printStackTrace();
45 }
46 }
47 }
Observe the screenshot, when no thread is suspended both threads are under execution.
WhenFirst thread goes into suspended state, the Second thread goes into action. Similarly,
when theSecond goes to suspended state, the First is executed.
Inter-thread communication in Java
52
critical section to be executed.It is implemented by following methods of Object class:
53
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws waits for the specified amount
InterruptedException of time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
54
Understanding the process of inter-thread communication
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
Let's see the important differences between wait and sleep methods.
wait() sleep()
55
wait() method releases the lock sleep() method doesn't release the lock.
56
is the method of Object class is the method of Thread class
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
57
30. public void run(){c.deposit(10000);}
58
31. }.start();
32.
33. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means continuous
flow of data. Streams are clean way to deal with input/output without having every part of
your code understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They
are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
59
These two abstract classes have several concrete classes that handle various devices such
as disk files, network connection etc.
DataOutputStream An output stream that contain method for writing java standard data
type
These classes define several key methods. Two most important are
60
2. : Writes byte of data.
write()
61
Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.
62
OutputStreamReader Output stream that translate character to byte.
We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function
returns integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
64
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new
InputstreamReader(System.in)); char c = (char)br.read(); //Reading
character
}
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
65
Program to read from a file using BufferedReader class
import java. Io *; class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ; String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
66
{
try
{
File fl = new File("d:/myfile.txt"); String str="Write this string to my file"; FileWriter fw = new FileWriter
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
67