Download Document

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Multithreading
in java
Overview
Multithreading in java is a process of executing multiple
threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of
processing. Multiprocessing and multithreading, both are used
to achieve multitasking.
But we use multithreading than multiprocessing because
threads share a common memory area. They don't allocate
separate memory area so saves memory, and contextswitching between the threads takes less time than
process.Java Multithreading is mostly used in games,
animation etc.
www.prolearninghub.com
Life Cycle of a Thread
A
thread
goes
through
various
stages in its life
cycle. For example,
a thread is born,
started, runs, and
then dies. The
following diagram
shows
the
complete life cycle
of a thread.
Runnable
New
Thread()
New
Running
Dead
Waiting
www.prolearninghub.com
Stages of the life cycle
Following are the stages of the life cycle −
New − A new thread begins its life cycle in the new state. It
remains in this state until the program starts the thread. It is
also referred to as aborn thread.
Runnable − After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be
executing its task.
www.prolearninghub.com
Stages of the life cycle
Waiting − Sometimes, a thread transitions
to the waiting state while the thread waits
for another thread to perform a task. A
thread transitions back to the runnable
state only when another thread signals the
waiting thread to continue executing.
www.prolearninghub.com
Stages of the life cycle
Timed Waiting − A runnable thread can enter the
timed waiting state for a specified interval of time.
A thread in this state transitions back to the
runnable state when that time interval expires or
when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the
terminated state when it completes its task or
otherwise terminates.
www.prolearninghub.com
Creating a thread in Java
There are two ways to create a thread in Java:
• By extending Thread class.
• By implementing Runnable interface.
Method of thread class
• getName(): It is used for Obtaining a thread’s name
• getPriority(): Obtain a thread’s priority
• isAlive(): Determine if a thread is still running
• join(): Wait for a thread to terminate
• run(): Entry point for the thread
• sleep(): suspend a thread for a period of time
• start(): start a thread by calling its run() method
www.prolearninghub.com
Thread creation by
extending Thread class
class MultithreadingDemo extends Thread{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output
My thread is in running state
www.prolearninghub.com
Thread creation by
implementing Runnable Interface
class MultithreadingDemo implements Runnable{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}
Output
My thread is in running state.
www.prolearninghub.com
Example #1
public class Worker implements Runnable {
public static void main (String[] args) {
System.out.println("This is currently running on the main thread, " +
"the id is: " + Thread.currentThread().getId());
Worker worker = new Worker();
Thread thread = new Thread(worker);
thread.start(); }
@Override
public void run() {
System.out.println("This is currently running on a separate thread, " +
}}
"the id is: " + Thread.currentThread().getId());
www.prolearninghub.com
Output
This is currently running on the main thread, the id is: 1
This is currently running on a separate thread, the id is: 9
www.prolearninghub.com
Thread Methods
Following is the list of important methods
available in the Thread class.
Method Name
public void start()
Description
Starts the thread in a separate path of execution, then
invokes the run() method on this Thread object.
public void run()
If this Thread object was instantiated using a separate
Runnable target, the run() method is invoked on that
Runnable object.
public final void setName(String name)
Changes the name of the Thread object. There is also a
getName() method for retrieving the name.
public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values
are between 1 and 10.
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon
thread.
www.prolearninghub.com
Thread Methods
Method Name
Description
public int getPriority()
returns the priority of the thread.
public String getName()
returns the name of the thread.
public Thread currentThread()
returns the reference of currently executing
thread.
public int getId()
returns the id of the thread.
public void resume()
is used to resume the suspended
thread(depricated).
public void stop():
is used to stop the thread(depricated).
www.prolearninghub.com
Thread Syncronization
When we start two or more threads within a program, there
may be a situation when multiple threads try to access the
same resource and finally they can produce unforeseen
result due to concurrency issues.
For example, if multiple threads try to write within a same file
then they may corrupt the data because one of the threads
can override data or while one thread is opening the same
file at the same time another thread might be closing the
same file.
www.prolearninghub.com
Thread Syncronization
So there is a need to synchronize the action of multiple
threads and make sure that only one thread can access the
resource at a given point in time. This is implemented using
a concept called monitors. Each object in Java is associated
with a monitor, which a thread can lock or unlock. Only one
thread at a time may hold a lock on a monitor.
www.prolearninghub.com
Thread Syncronization
Java programming language provides a very handy way of
creating threads and synchronizing their task by
using synchronized blocks. You keep shared resources
within this block. Following is the general form of the
synchronized statement.
Syntax
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
www.prolearninghub.com
Thread Priorities
Every Java thread has a priority that helps the operating
system determine the order in which threads are scheduled.
Java thread priorities are in the range between
MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a
constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program
and should be allocated processor time before lower-priority
threads. However, thread priorities cannot guarantee the order
in which threads execute and are very much platform
dependent.
www.prolearninghub.com