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

Multithread Programming

The document discusses multithreading in Java. It defines threads and describes how to create threads by extending the Thread class and implementing the Runnable interface. It also covers thread life cycle states, priorities, and synchronization.

Uploaded by

Devesh Surana
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Multithread Programming

The document discusses multithreading in Java. It defines threads and describes how to create threads by extending the Thread class and implementing the Runnable interface. It also covers thread life cycle states, priorities, and synchronization.

Uploaded by

Devesh Surana
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

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

 The process of executing multiple threads simultaneously is


known as multithreading.

 A multi-threaded program contains two or more parts that can run


concurrently and each part can handle a different task.
A multithreaded program
Creating a Thread
 Thread are implemented in the form of objects that contain a
method called run().
 It makes up the entire body of a thread and is the only method in
which thread’s behavior can be implemented.
 Syntax:
public void run()
{
….//statement for implementing thread
}
Ways to create Thread
 By extending the Thread class
define a class that extends Thread class and
override its run() method with the code required by the
thread

 By implementing Runnable interface


define a class that implements Runnable
interface. The Runnable interface has only one method,
run().
Extending the Thread class

Steps to create a Thread by extending Thread class:


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.
1. Declaring the class

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.

Situations when Thread may release its control:


1. It has been suspended using suspend() method. A suspended thread can
be resumed by using the resume() method.
2. It has been made to sleep. We can put a thread to sleep for a specified time
period using the method sleep(time) where time is in milliseconds.

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

 A running thread ends its life when it has completed executing


its run() method. It is a natural death.
 However, we can kill it by sending the stop message to it using
stop() method. It is called premature death.
 A thread can be killed as soon as it is born, or while it is
running, or even when it is in blocked condition.
Example
class A extends Thread
{
public void run(){
for(int i=1;i<=5;i++)
{
if(i==2)
yield();
System.out.println("Running Thread A: "+i);
}
System.out.println("exit from thread A");
}
} Contd…
Contd… class B extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
{
System.out.println("Running Thread B: "+i);
if(i==3)
stop();
}
System.out.println("exit from thread B");
}
} Contd…
Contd.. class C extends Thread{
public void run(){
for(int i=1;i<=3;i++)
{
System.out.println("Running Thread C: "+i);
if(i==1)
try
{ sleep(1000); }
catch(Exception e)
{ System.out.println(e); }
}
System.out.println("exit from thread C");
}} Contd..
Contd..
class ExpThread
{
public static void main(String args[]){
A t1=new A();
t1.start();
B t2=new B();
t2.start();
C t3=new C();
t3.start();
}
}
Output
Thread Exception
 Java run system will throw IllegalThreadStateException
whenever we attempt to invoke a method that a thread cannot
handle in the given state.

 e.g. a sleeping thread cannot deal with the resume() method


because a sleeping thread cannot receive any instructions.
Thread Priority
 In java, each thread is assigned a priority, which affects the order in
which it is scheduled for running.
 The threads of the same priority share the processor on a first-come, first-
serve basis.
 To set a thread priority setPriority() method is used.
 Syntax:
ThreadName.setPriority(intnumber);
Where, intnumber is an integer value to which the Thread’s priority is set.
 Priority Constants:
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
class A extends Thread {
E public void run(){
x for(int i=1;i<=5;i++)
a { System.out.println("Running Thread A: "+i); }
m System.out.println("exit from thread A");
pl }
e }
class B extends Thread {
public void run(){
for(int i=1;i<=3;i++)
{ System.out.println("Running Thread B: "+i); }
System.out.println("exit from thread B");
}} Contd…
class C extends Thread{
Contd…
public void run(){
for(int i=1;i<=3;i++)
{ System.out.println("Running Thread C: "+i); }
System.out.println("exit from thread C");
}
}
class ThreadPriority
{
public static void main(String args[]){
A t1=new A();
B t2=new B();
C t3=new C(); Contd…
Contd…

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.

 Java Synchronization is better option where we want to allow only


one thread to access the 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);
}

}catch(Exception e){System.out.println(e);} public class TestSynchronizedBlock1{


} } }//end of the method } 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); } }
Implementing the Runnable interface

Steps to implement Runnable interface:

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.
4. Call the Thread’s start() method to run the thread.
Example
class A implements Runnable //step 1
{
public void run() //step 2
{
for(int i=1;i<=5;i++)
{
System.out.println("i="+i);
}
}
} contd…
contd…
class RunnableTest
{
public static void main(String args[])
{
A t=new A();
Thread ta=new Thread(t); //step 3
ta.start(); //step 4
//new Thread(new A()).start(); // shortcut for above 3 lines
}
}

You might also like