Sie sind auf Seite 1von 40

Threads in JAVA

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();
}
}

O/P: Name of t1:Thread-0


After changing name of t1:MY THREAD
running...
currentThread() method
• The currentThread() method returns a reference to the currently executing thread object.

class CurrentThreadDemo extends Thread{


public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]){
CurrentThreadDemo t1=new CurrentThreadDemo();
CurrentThreadDemo t2=new CurrentThreadDemo();
t1.setName("First Thread");
t2.setName("Second Thread");
t1.start();
t2.start(); O/P: First Thread
} Second Thread
}
Priority of a Thread
• Each thread has a priority.
• Priorities are represented by a number between 1 and 10.
• In most cases, thread scheduler schedules the threads according to their priority
(known as pre-emptive scheduling). But it is not guaranteed because it depends
on JVM specification that tells which scheduling it chooses.
• These priorities are defined as final variable within Thread class.
 public static final int MIN_PRIORITY
 public static final int NORM_PRIORITY
 public static final int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Thread Priority Example
class ThreadPriorityDemo extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority()); }
public static void main(String args[]){
ThreadPriorityDemo m1=new ThreadPriorityDemo();
ThreadPriorityDemo m2=new ThreadPriorityDemo();
m1.setName("Thread of m1");
m2.setName("Thread of m2");
m1.setPriority(Thread.MIN_PRIORITY+3);
O/P: running thread name is:Thread of m2
m2.setPriority(Thread.MAX_PRIORITY-3); running thread priority is:7
m1.start(); running thread name is:Thread of m1
m2.start(); running thread priority is:4
} }

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; }

public SynchronizedMethodDemo(BaseClass ob, String msg){ }


obj=ob;
message=msg;
t=new Thread(this); O/P: [Welcome]
t.start();} [To]
public void run(){ [Thread Programming]
Synchronization Block
• Creating a synchronized method will not work in all cases.
• Suppose you want to synchronize access to objects of a class that was not
designed for multithreaded access i.e. this class does not use synchronized
methods. Further, this class is not created by you, but by a third party and you
don’t have access to the source code. Thus, we can’t add the synchronized to
appropriate method in the class.
• So, How access to the objects of this class can be synchronized?
• This problem is solved by using synchronized block by placing the calls to the
methods inside the synchronized block.

synchronized(object) //object is a reference to the object being synchronized


{
//statements to be synchronized
}
Using synchronized keyword
class BaseClass{ Synchronized(obj)
void PrintMessage(String msg){ {
System.out.print("["+ msg); obj.PrintMessage(message);
System.out.println("]"); }
} }
} public static void main(String[] args)
public class SynchronizedMethodDemo implements Runnable {
{ BaseClass b1=new BaseClass();
String message; SynchronizedMethodDemo smd1=new
SynchronizedMethodDemo(b1, "Welcome");
BaseClass obj;
SynchronizedMethodDemo smd2=new
Thread t; SynchronizedMethodDemo(b1, "To");
public SynchronizedMethodDemo(BaseClass ob, String msg){ SynchronizedMethodDemo smd3=new
obj=ob; SynchronizedMethodDemo(b1, "Thread Programming");

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.

2) It is the method of Object class 2) It is the method of Thread class

3) It is the non-static method 3) It is the static method


Daemon Thread in Java
• Daemon thread in java is a service provider thread that provides services to the
user thread. Its life depends on the mercy of user threads i.e. when all the user
threads dies, JVM terminates this thread automatically.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.
Points to remember for Daemon Thread in Java
 It provides services to user threads for background supporting tasks. It has no
role in life than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.
Demon thread Example
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){ //checking for daemon thread
System.out.println(“I am daemon thread.");
}
else{
System.out.println(“ I am user thread."); }
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1(); //creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true); //now t1 is daemon thread
t1.start(); //starting threads O/P: I am daemon thread.
t2.start(); I am user thread.
t3.start(); I am user thread.
}
Demon thread Example
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){ //checking for daemon thread
System.out.println(“I am daemon thread.");
} Note: If you want to make a user thread as
else{ Daemon, it must not be started otherwise it
System.out.println(“ I am user thread."); } will throw IllegalThreadStateException.
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1(); //creating thread
TestDaemonThread1 t2=new TestDaemonThread1(); O/P: Exception in thread "main" I
TestDaemonThread1 t3=new TestDaemonThread1(); am user thread.
t1.start(); //starting threads java.lang.IllegalThreadStateException
t1.setDaemon(true); //now t1 is daemon thread at java.lang.Thread.setDaemon(Unknown
t2.start(); Source) at
t3.start(); TestDaemonThread1.main(TestDaemonThre
} ad1.java:14)
Can we start a thread twice?
No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for second
time, it will throw exception.

public class StartThreadTwiceDemo extends Thread{


public void run(){
System.out.println("running...");
}
public static void main(String args[]){
StartThreadTwiceDemo t1=new StartThreadTwiceDemo();
t1.start();
t1.start(); O/p:
running …
}
Exception in thread "main" java.lang.IllegalThreadStateException
}
What if we call run() method directly
instead start() method
class TestCallRun2 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
} 2
} 3
public static void main(String args[]){ 4
TestCallRun2 t1=new TestCallRun2(); 1
TestCallRun2 t2=new TestCallRun2(); 2
3
t1.run(); //fine, but does not start a separate call stack 4
t2.run();
}
}
Reason behind the scene
• Each thread starts in a separate call stack.
• Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.

• In the previous program there will be no context-switching because t1 and t2 will


be treated as normal object not thread object.
……MCQs……
In java, a thread can be created by ..........

A. Extending the thread class.

B. Implementing Runnable interface.

C. Both of the above

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

D. None of the above


What notifyAll() method do?

A. Wakes up one threads that are waiting on this object's monitor

B. Wakes up all threads that are not waiting on this object's monitor

C. Wakes up all threads that are waiting on this object's monitor

D. None of the above


Which keyword when applied on a method indicates that only one
thread should execute the method at a time?

A. volatile

B. synchronized

C. native

D. static

E. final
THANK YOU

Das könnte Ihnen auch gefallen