Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Multitasking in Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 8

Multitasking in Java

• It is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved in two ways:
1) Process-based Multitasking (Multiprocessing)
• Each process has an address in memory. In other words, each process allocates a separate memory
area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and loading registers, memory
maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
Multithreading in Java

• It is a process of executing multiple threads simultaneously.

• A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

• However, we use multithreading than multiprocessing because threads use a shared memory area. They
don't allocate separate memory area so saves memory, and context-switching between the threads takes
less time than process.
• Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
What is Thread in java
• A thread is a lightweight sub process, the smallest unit of processing. It is a separate path of
execution.
• Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.
• Java provides Thread class to achieve thread programming. Thread class provides constructors
and methods to create and perform operations on a thread. Thread class extends Object class and
implements Runnable interface.
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states. These states are:
1.New - Whenever a new thread is created, it is always in the new state. For a thread in the new state, the
code has not been run yet and thus has not begun its execution.
2.Active - When a thread invokes the start() method, it moves from the new state to the active state. The
active state contains two states within it: one is runnable, and the other is running.
3.Blocked / Waiting - A thread, that is ready to run is then moved to the runnable state. In the runnable
state, the thread may be running or may be ready to run at any given instant of time. It is the duty of the
thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
4.Timed Waiting - Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has
entered the critical section of a code and is not willing to leave that critical section. In such a scenario,
another thread (its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a
timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time,
and not forever.
5.Terminated - A thread reaches the termination state because of the following reasons:
•When a thread has finished its job, then it exists or terminates normally.
•Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
Java Threads | How to create a thread in Java

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 thread. Thread 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)
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:

The start() method of Thread class is used to start a newly created thread. It performs the 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.
class Multi extends Thread{ class Multi3 implements Runnable{
public void run(){ public void run(){
System.out.println("thread is running..."); System.out.println("thread is running...");
} }
public static void main(String args[]){ public static void main(String args[]){
Multi t1=new Multi(); Multi3 m1=new Multi3();
t1.start(); Thread t1 =new Thread(m1); // Using the constructor Thread
} (Runnable r)
} t1.start();
}
}
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 thread. JVM calls the run() method on the thread.
3.public void sleep(long milliseconds): 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 milliseconds): waits for a thread to die for the specified milliseconds.
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 Thread.State 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.

You might also like