0b6at Wuxbp6ldWN1RWt6ZS1oWnZvbk5qTFYwdHVSSGxWYkV3
0b6at Wuxbp6ldWN1RWt6ZS1oWnZvbk5qTFYwdHVSSGxWYkV3
0b6at Wuxbp6ldWN1RWt6ZS1oWnZvbk5qTFYwdHVSSGxWYkV3
What is Thread?
• A thread is a lightweight process, a smallest unit of processing.
• Threads are independent, if there occurs exception in one thread, it
doesn't affect other threads. It shares a common memory area.
• Multithreading in java is a process of executing multiple threads
simultaneously.
Note:
At least one process is required for each thread.
At a time one thread is executed only. There is context-switching
between the threads.
Thread Life Cycle
• A thread can be in one of the five states.
• The life cycle of the thread in java is controlled by JVM. The java
thread states are as follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
Thread Life Cycle
• 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 has not selected it to be the running thread.
• 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
A thread is in terminated or dead state when its run() method exits.
Thread Life Cycle
Creating thread in JAVA
• There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
• 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.
• Runnable interface
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread.
Creating thread by extending Thread class
• Commonly used Constructors of Thread class
Thread()
Thread(String name)
Commonly used methods of Thread class
public void run(): is used to perform action for a public int getId(): returns the id of the thread.
thread.
public Thread.State getState(): returns the state of
public void start(): starts the execution of the thread. the thread.
JVM calls the run() method on the thread.
public boolean isAlive(): tests if the thread is alive.
public static void sleep(long miliseconds): Causes
the currently executing thread to sleep (temporarily public void suspend(): is used to suspend the
cease execution) for the specified number of thread(depricated).
milliseconds. public void resume(): is used to resume the
public void join(): waits for a thread to die. suspended thread(depricated).
public void join(long miliseconds): waits for a public void stop(): is used to stop the
thread to die for the specified miliseconds. thread(depricated).
public int getPriority(): returns the priority of the public boolean isDaemon(): tests if the thread is a
thread. daemon thread.
public int setPriority(int priority): changes the public void setDaemon(boolean b): marks the
priority of the thread. thread as daemon or user thread.
public String getName(): returns the name of the public void interrupt(): interrupts the thread.
thread. public boolean isInterrupted(): tests if the thread
public void setName(String name): changes the has been interrupted.
name of the thread.
public Thread currentThread(): returns the
reference of currently executing thread.
Creating thread by implementing
Runnable Interface
• Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
• Starting a thread
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
Using Thread Class Example
class CreatingThreadUsingThreadClassDemo extends Thread{
public void run(){
System.out.println("thread created using Thread Class...");
}
public static void main(String args[]){
CreatingThreadUsingThreadClassDemo t1=new CreatingThreadUsingThreadClassDemo();
t1.start();
}
}
O/P: thread created using Thread Class...
Using Runnable Interface
class CreatingThreadUsingRunnableDemo implements Runnable{
public void run(){
System.out.println("thread created using Runnable Interface...");
}
public static void main(String args[]){
CreatingThreadUsingRunnableDemo obj=new CreatingThreadUsingRunnableDemo();
Thread t1 =new Thread(obj);
t1.start();
}
}
O/P: thread created using Runnable Interface...
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.
Sleep() method
• The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.
class TestSleepMethod extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i); O/P: 1
} } 1
public static void main(String args[]){ 2
2
TestSleepMethod t1=new TestSleepMethod(); 3
TestSleepMethod t2=new TestSleepMethod(); 3
t1.start(); 4
4
t2.start(); 5
}} 5
Join() Method
class JoinMethodDemo extends Thread{ t1.start();
public void run(){ try{
for(int i=1;i<=5;i++){ t1.join();
try{ }catch(Exception e){System.out.println(e);} O/P: 1
Thread.sleep(500); t2.start(); 2
3
}catch(Exception e){System.out.println(e);} t3.start(); 4
System.out.println(i); } 5
1
} } 1
} 2
2
public static void main(String args[]){ 3
JoinMethodDemo t1=new JoinMethodDemo(); 3
4
JoinMethodDemo t2=new JoinMethodDemo(); 4
5
JoinMethodDemo t3=new JoinMethodDemo();
5
Naming Thread
• The Thread class provides methods to change and get the name of a thread.
• By default, each thread has a name i.e. thread-0, thread-1 and so on.
• We can change the name of the thread by using setName() method. The syntax of
setName() and getName() methods are given below:
public String getName(): is used to return the name of a thread.
public void setName(String name): is used to change the name of a thread.
Example of naming a thread
class NamingThreadDemo extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
NamingThreadDemo t1=new NamingThreadDemo();
System.out.println("Name of t1:"+t1.getName());
t1.setName("MY THREAD");
System.out.println("After changing name of t1:"+t1.getName());
t1.start();
}
}
Note: When this same program is run under a non pre-emptive system, different
result will be obtained.
Thread Synchronization
• When two or more threads need to access a shared resource, they need some way
to ensure that the resources will be used by the only one thread at a time. The
process by which it is achieved is called synchronization.
• A monitor is an object that is used as mutually exclusive lock or mutex. Only one
thread can own a monitor at a given time.
• When a thread acquires a lock, it is said to have entered the monitor.
• All other threads attempting to enter the monitor will be suspended until the first
thread exits the monitor.
• Synchronization between threads can be achieved by two ways:
By using synchronized method.
By using synchronized block.
Example without synchronized method
class BaseClass{ obj.PrintMessage(message);
void PrintMessage(String msg){ }
System.out.print("["+ msg); public static void main(String[] args)
System.out.println("]"); {
}} BaseClass b1=new BaseClass();
public class SynchronizedMethodDemo implements Runnable SynchronizedMethodDemo smd1=new
SynchronizedMethodDemo(b1, "Welcome");
{
SynchronizedMethodDemo smd2=new
String message; SynchronizedMethodDemo(b1, "To");
BaseClass obj; SynchronizedMethodDemo smd3=new
Thread t; SynchronizedMethodDemo(b1, "Thread Programming");
public SynchronizedMethodDemo(BaseClass ob, String msg) }
{ }
obj=ob;
message=msg;
t=new Thread(this); O/P: [Welcome[To]
t.start();} [Thread Programming]
public void run(){ ]
Using synchronized keyword
class BaseClass{ obj.PrintMessage(message);
synchronized void PrintMessage(String msg){ }
System.out.print("["+ msg); public static void main(String[] args)
System.out.println("]"); {
} BaseClass b1=new BaseClass();
} SynchronizedMethodDemo smd1=new
SynchronizedMethodDemo(b1, "Welcome");
public class SynchronizedMethodDemo implements Runnable
SynchronizedMethodDemo smd2=new
{ SynchronizedMethodDemo(b1, "To");
String message; SynchronizedMethodDemo smd3=new
BaseClass obj; SynchronizedMethodDemo(b1, "Thread Programming");
Thread t; }
message=msg; }
t=new Thread(this); }
O/P: [Welcome]
t.start();} [To]
public void run(){ [Thread Programming]
Inter Thread Communication
• Inter-thread communication is allowing synchronized threads to
communicate with each other.
• Inter-thread communication is a mechanism in which a thread is
paused running in its critical section and another thread is allowed to
enter (or lock) in the same critical section to be executed. It is
implemented by following methods of Object class:
wait()
notify()
notifyAll()
wait(), notify(), notifyAll() methods
• wait() tells the calling thread to give up the monitor and to sleep until
some other thread enters the same monitor and calls notify().
• notify() wakes up the first thread that called wait() on the same object.
• notifyAll() wakes up all the threads that called wait() on the same
object. The highest priority thread will run first.
• These methods are declared within Object class, as:
final void wait() throws InterruptedException
final void notify()
final void notifyAll()
Example of Inter Thread Communication
class Customer{ System.out.println("deposit completed... ");
int amount=10000; notify();
}
synchronized void withdraw(int amount){ }
System.out.println("going to withdraw..."); class InterThreadCommunicationDemo{
if(this.amount<amount){ public static void main(String args[]){
System.out.println("Less balance; waiting for deposit..."); Customer c=new Customer();
try{wait();}catch(Exception e){} new Thread(){
} public void run(){c.withdraw(15000);}
this.amount-=amount; }.start();
System.out.println("withdraw completed..."); new Thread(){
} public void run(){c.deposit(10000);}
O/P: going to withdraw...
synchronized void deposit(int amount){ }.start();
Less balance; waiting for deposit...
System.out.println("going to deposit..."); }} going to deposit...
this.amount+=amount; deposit completed...
withdraw completed...
Difference between wait() and sleep()
wait() sleep()
1) wait() method releases the lock 1) sleep() method doesn't release the lock.
D. None of these
What will be the output?
class One extends Thread Test t = new Test();
{ t.call(new One());
public void run() }
{ public void call(One o){
for(int i=0; i<2; i++) o.start();
{ }
System.out.print(i); }
}
} A. 0 0
}
public class Test B. Compilation Error
{ C. 0 1
public static void main(String args[])
{ D. None of these
Predict the output…
class A implements Runnable{ {
public void run(){ A a = new A();
try{ Thread t = new Thread(a, "A");
for(int i=0;i<4;i++){ Thread t1 = new Thread(a, "B");
Thread.sleep(100); t.start();
System.out.println(Thread.currentThread().getName());
t.join();
} t1.start();
}catch(InterruptedException e){ }}
}
A. A A A A B B B B
} B. A B A B A B A B
} C. Output order is not guaranteed
public class Test{
D. Compilation succeed but Runtime Exception
public static void main(String argv[]) throws Exception E. None of these
Which of the following are methods of the Thread class?
1) yield()
2) sleep(long msec)
3) go()
4) stop()
A. 1 , 2 and 4
B. 1 and 3
C. 3 only
B. Wakes up all threads that are not waiting on this object's monitor
A. volatile
B. synchronized
C. native
D. static
E. final
THANK YOU