0% found this document useful (0 votes)
27 views11 pages

Multithread

Uploaded by

Abenzer Mulugeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views11 pages

Multithread

Uploaded by

Abenzer Mulugeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Contribute Us | Ask Question | login

Subscribe Us
91-9990449935
0120-4256464

 Home
 Core Java
 Servlet
 JSP
 EJB
 Struts2
 Mail
 Hibernate
 Spring
 Android
 Design P
 Quiz
 Projects
 Interview Q
 Comment
 Forum
 Training

Basics of JavaOOPs ConceptsJava StringJava RegexException HandlingJava Inner classes


Java Multithreading
What is MultithreadingLife Cycle of a ThreadCreating ThreadThread SchedulerSleeping a
threadStart a thread twiceCalling run() methodJoining a threadNaming a threadThread
PriorityDaemon ThreadThread PoolThread GroupShutdownHookPerforming multiple
taskGarbage CollectionRuntime classMultithreading quiz-1Multithreading quiz-2
Java Synchronization
Synchronization in javasynchronized blockstatic synchronizationDeadlock in JavaInter-thread
CommInterrupting ThreadReentrant Monitor
Java I/OJava NetworkingJava AWTJava SwingJava AppletJava ReflectionJava DateJava
ConversionJava CollectionJava JDBCJava New FeaturesRMIInternationalizationInterview
Questions
Subscribe Us
91-9990449935
0120-4256464

 Home
 Core Java
 Servlet
 JSP
 EJB
 Struts2
 Mail
 Hibernate
 Spring
 Android
 Design P
 Quiz
 Projects
 Interview Q
 Comment
 Forum
 Training

Basics of JavaOOPs ConceptsJava StringJava RegexException HandlingJava Inner classes


Java Multithreading
What is MultithreadingLife Cycle of a ThreadCreating ThreadThread SchedulerSleeping a
threadStart a thread twiceCalling run() methodJoining a threadNaming a threadThread
PriorityDaemon ThreadThread PoolThread GroupShutdownHookPerforming multiple
taskGarbage CollectionRuntime classMultithreading quiz-1Multithreading quiz-2
Java Synchronization
Synchronization in javasynchronized blockstatic synchronizationDeadlock in JavaInter-thread
CommInterrupting ThreadReentrant Monitor
Java I/OJava NetworkingJava AWTJava SwingJava AppletJava ReflectionJava DateJava
ConversionJava CollectionJava JDBCJava New FeaturesRMIInternationalizationInterview
Questions

next>><<prev

Life cycle of a Thread (Thread States)


1. Life cycle of a thread
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

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.

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)
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
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.

Next TopicCreating Thread

<<prevnext>>

///////////////

Subscribe Us
91-9990449935
0120-4256464

 Home
 Core Java
 Servlet
 JSP
 EJB
 Struts2
 Mail
 Hibernate
 Spring
 Android
 Design P
 Quiz
 Projects
 Interview Q
 Comment
 Forum
 Training

Basics of JavaOOPs ConceptsJava StringJava RegexException HandlingJava Inner classes


Java Multithreading
What is MultithreadingLife Cycle of a ThreadCreating ThreadThread SchedulerSleeping a
threadStart a thread twiceCalling run() methodJoining a threadNaming a threadThread
PriorityDaemon ThreadThread PoolThread GroupShutdownHookPerforming multiple
taskGarbage CollectionRuntime classMultithreading quiz-1Multithreading quiz-2
Java Synchronization
Synchronization in javasynchronized blockstatic synchronizationDeadlock in JavaInter-thread
CommInterrupting ThreadReentrant Monitor
Java I/OJava NetworkingJava AWTJava SwingJava AppletJava ReflectionJava DateJava
ConversionJava CollectionJava JDBCJava New FeaturesRMIInternationalizationInterview
Questions

next>><<prev

How to create thread


There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run()
method 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 [Link] 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().
1. 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.

1)By extending Thread class:


1. class Multi extends Thread{
2. public void run(){
3. [Link]("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. [Link]();
8. }
9. }

Output:thread is running...

Who makes your class object as thread object?

Thread class constructor allocates a new thread [Link] you create object of
Multi class,your class constructor is invoked(provided by Compiler) fromwhere Thread
class constructor is invoked(by super() as first statement).So your Multi class object is
thread object now.

2)By implementing the Runnable interface:


1. class Multi3 implements Runnable{
2. public void run(){
3. [Link]("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. [Link]();
10. }
11. }

Output:thread is running...

If you are not extending the Thread class,your class object would not be treated as a
thread [Link] you need to explicitely create Thread class [Link] are passing the
object of your class that implements Runnable so that your class run() method may
execute.
Next TopicThread Schedular

<<prevnext>>

Thread Scheduler in Java


Thread scheduler in java is the part of the JVM that decides which thread should run.

There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.

Only one thread at a time can run in a single process.

The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.

Difference between preemptive scheduling and time


slicing
Under preemptive scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other
factors.

Next TopicSleeping a thread

<<prevnext>>

/////////////////////////

Contribute Us | Ask Question | login

Subscribe Us
91-9990449935
0120-4256464

 Home
 Core Java
 Servlet
 JSP
 EJB
 Struts2
 Mail
 Hibernate
 Spring
 Android
 Design P
 Quiz
 Projects
 Interview Q
 Comment
 Forum
 Training

Basics of JavaOOPs ConceptsJava StringJava RegexException HandlingJava Inner classes


Java Multithreading
What is MultithreadingLife Cycle of a ThreadCreating ThreadThread SchedulerSleeping a
threadStart a thread twiceCalling run() methodJoining a threadNaming a threadThread
PriorityDaemon ThreadThread PoolThread GroupShutdownHookPerforming multiple
taskGarbage CollectionRuntime classMultithreading quiz-1Multithreading quiz-2
Java Synchronization
Synchronization in javasynchronized blockstatic synchronizationDeadlock in JavaInter-thread
CommInterrupting ThreadReentrant Monitor
Java I/OJava NetworkingJava AWTJava SwingJava AppletJava ReflectionJava DateJava
ConversionJava CollectionJava JDBCJava New FeaturesRMIInternationalizationInterview
Questions

next →← prev

Sleep method in java


The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

o public static void sleep(long miliseconds)throws InterruptedException


o public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java


1. class TestSleepMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<5;i++){
4. try{[Link](500);}catch(InterruptedException e){[Link](e);}
5. [Link](i);
6. }
7. }
8. public static void main(String args[]){
9. TestSleepMethod1 t1=new TestSleepMethod1();
10. TestSleepMethod1 t2=new TestSleepMethod1();
11.
12. [Link]();
13. [Link]();
14. }
15. }

Output:

1
1

As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.

Next TopicCan we start a Thread Twice

← prevnext →

You might also like