Multithread Programming
Multithread Programming
Threads
A thread is a light-weight smallest part of a process that can run
concurrently with the other parts(other threads) of the same
process.
Threads are independent because they all have separate path of
execution that’s the reason if an exception occurs in one thread,
it doesn’t affect the execution of other threads.
All threads of a process share the common memory.
Thread in java
Single threaded program
Multithreading
Syntax:
class classname extends Thread
{ …………}
Example
class myThread extends Thread
{ ……….}
2. Implementing the run() method
The run() method has been inherited by the subclass
which we created previously.
We have to override this method in order to implement
the code to be executed by our thread.
Syntax :
public void run()
{
……//Thread code
}
3. Starting new Thread
Syntax:
classname objectname=new classname();
objectname.start();
Example :
MyThread t=new MyThread();
t.start();
Example class MultiT1 extends Thread{
public void run(){
for(int i=1;i<=3;i++)
{ System.out.println("Running Thread 1: "+i); }
System.out.println("exit from thread 1");
}
}
class MultiT2 extends Thread{
public void run(){
for(int i=1;i<=3;i++)
{ System.out.println("Running Thread 2: "+i);}
System.out.println("exit from thread 2");
contd…
contd…
}
}
class MyThread
{
public static void main(String args[]){
MultiT1 t1=new MultiT1();
t1.start();
MultiT2 t2=new MultiT2();
t2.start();
}
}
Output1 Output2 output3
Life cycle of a Thread
During life cycle of a thread, there are many states it can enter.
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Thread Life cycle
Newborn state
When we create a thread object, the thread is born and is said to be in
newborn state.
The thread is not yet schedule for running.
We can do only one of the following things with it:
Schedule it for running using start() method
Kill it using stop() method
If we attempt to use any other method at this stage, an exception will be
thrown.
Runnable state
The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor.
The threads has joined the queue of threads that are waiting for
execution.
If we want a thread to release its control for another thread of equal
priority before its turn comes, we can do so by using yield() method.
Running state
Running means that the processor has given its time to the thread for its
execution.
The thread runs until it releases control on its own or preempted by a
higher priority thread.
3. It has been told to wait until some event occurs. This is done using wait()
method. The thread can be scheduled to run again using the notify() method.
Blocked state
A thread is said to be blocked when it is prevented from entering
into the runnable state and subsequently in running state.
A blocked thread is considered not runnable but not dead.
A thread can blocked using following methods:
sleep() : blocked for specific time
suspend() : blocked until further orders
wait() : blocked until certain condition occurs
Dead state
t3.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(t1.getPriority()+1);
t1.setPriority(Thread.MIN_PRIORITY);
System.out.println("start of thread A");
t1.start();
System.out.println("start of thread B");
t2.start();
System.out.println("start of thread C");
t3.start();
}
}
Output
Synchronization
Synchronization in java is the capability to control the access of
multiple threads to any shared resource.
E.g. one thread may try to read a record from a file while another
is still writing to the same file. At this time we may get strange
result. To overcome this problem synchronization is used.
Synchronized method
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the
lock for that object and releases it when the thread completes its task.
When we declare a method synchronized, java created a monitor and hands it
over to the thread that calls the method first time. As long as the thread
holds monitor, no other thread can enter the synchronized section of code. A
monitor is a key and the thread that holds the key can only open the lock.
E.g.
synchronized void update()
{ ……..
}
Synchronized block
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.
Syntax:
synchronized (object reference expression)
{
//code block
}
class Table{ class MyThread2 extends Thread{
Table t;
void printTable(int n){//method not synchronized MyThread2(Table t){
for(int i=1;i<=5;i++){ this.t=t;
System.out.println(n*i); }
public void run(){
try{ t.printTable(100);
Thread.sleep(400); }
}catch(Exception e){System.out.println(e);}
}
} } class TestSynchronization1{
} public static void main(String args[]){
Table obj = new Table();//only one object
class MyThread1 extends Thread{
MyThread1 t1=new MyThread1(obj);
Table t; MyThread2 t2=new MyThread2(obj);
MyThread1(Table t){ t1.start();
t2.start();
this.t=t;
}
} }
public void run(){
t.printTable(5);
}
class Table class MyThread2 extends Thread{
Table t;
{ void printTable(int n){
MyThread2(Table t){
synchronized(this){//synchronized block this.t=t;
for(int i=1;i<=5;i++){ }
public void run(){
System.out.println(n*i);
t.printTable(100);
try{ }
Thread.sleep(400);
}
t.printTable(5); } }
Implementing the Runnable interface