0% found this document useful (0 votes)
4 views6 pages

Java Multithreading Explained

The document discusses multithreading in Java. It explains that multithreading allows parts of a program to run concurrently by using threads. It describes how to create and manage threads using the Thread class or by implementing the Runnable interface. It also covers thread priorities and context switching between threads.

Uploaded by

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

Java Multithreading Explained

The document discusses multithreading in Java. It explains that multithreading allows parts of a program to run concurrently by using threads. It describes how to create and manage threads using the Thread class or by implementing the Runnable interface. It also covers thread priorities and context switching between threads.

Uploaded by

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

multithreading in java

two or more parts run concurrently - multitasking

each part is called a thread

each thread defines separate part of execution

multitasking - process based or thread based

process based - runs 2 or more programs concurrently

thread based - in a single program, 2 or more tasks are


performed simultaneously

difference in process based and thread based

process based thread based

1) more overhead 1) less overhead

2) heavyweight tasks that require 2) lightweight tasks that can


their own address spaces share address spaces

3) context switching is
3) context switching is expensive
inexpensive

4) interprocess communication is 4) interthread communication is


expensive and limited inexpensive

5) not under control of java 5) under control of java

multithreading better than single thread environment -


allows efficient use of CPU keeping the idle time of CPU to
a minimum

thread priorities - decides when to switch from one running


thread to next

rules that decide context switching

voluntarily relinquishing control - yielding, sleeping


or blocking - highest priority thread is given to CPU

multithreading in java 1
preempted by higher priority thread - lower priority
thread that does not yield the processor is preempted by
higher priority thread - preemptive multitasking

multithreading is done using

thread class

runnable interface

methods defined by thread class

method meaning

getName() get a thread’s name

getPriority() get thread’s priority

isAlive() check if thread is running

join() wait for thread to terminate

run() entry point for thread

sleep() suspend thread for a period of time

start() start a thread

setName(String threadName) set thread’s name

main thread -

if a java program is started - main thread executes


immediately

child threads are spawned from here

last thread to finish execution - performs shutdown


actions

controlled using Thread object

call method currentThread() - public static member of


thread

syntax : static Thread currentThread()

multithreading in java 2
ways to start a thread using runnable interface

class MyThread
class MyThread
implements Runnable
implements Runnable
{
{
Thread t2;
public void run()
MyThread()
{
{
t2 = new Thread(this);
}
[Link]();
}
}
public void run()
class prg
{
{
}
public static void
}
main(String[]args)
class prg
{
{
MyThread t = new
public static void
MyThread();
main(String args[])
Thread t2 = new
{
Thread(t);
MyThread t = new
[Link]();
MyThread();
}
}
}
}

explanation : made a explanation : made a


class MyThread which class MyThread which
implements Runnable implements Runnable
interface - indicates interface - indicates
that instances of this that instances of this
class can be executed class can be executed
by a thread by a thread

public void run : Thread t2 declares


declares a method named variable t2 of type
run which is required Thread - used to store
to be implemented when reference to Thread
a class implements the object
runnable interface -
this method contains MyThread() -
the code to be executed constructor of MyThread
when thread is started class
in main class

multithreading in java 3
t2 = new Thread(this)
MyThread t = new creates a new Thread
MyThread() creates an object t2 and
instance of MyThread associates it with
class t which can be current instance of
used to start a new MyThread (which
thread explains use of this
keyword)
Thread t2 = new
Thread(t) - creates a [Link]() starts the
new Thread object t2 thread t2 - invokes run
and associates it with method of MyThread
MyThread instance t by instance
passing t as a
parameter to Thread() public void run :
constructor declares a method named
run which is required
[Link]() starts the to be implemented when
thread - invokes the a class implements the
run method of MyThread runnable interface -
instance t this method contains
the code to be executed
when thread is started
in main class
in main class,
MyThread t = new
MyThread() creates an
instance of MyThread
triggering constructor
and a new thread is
started

creating a thread

1) implementing runnable interface

to implement runnable, a class needs to implement run


method

inside run(), we define the code that constitutes the


new thread

run() establishes an entry point for another concurrent


thread of execution within our program

multithreading in java 4
then instantiate an object of type Thread from within
the class that implements runnable

2) extending thread class

extending class must override run() method - entry point


for new thread

must also call start() method to begin execution of new


thread

class NewThread extends Thread


{
NewThread()
{
super("Demo Thread");
[Link]("Child thread: " +
this);
start(); // Start the thread
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
[Link]("Child Thread: " + i);
[Link](500);
}
}
catch (InterruptedException e)
{
[Link]("Child interrupted.");
}
[Link]("Exiting child
thread.");
}
}

class ExtendThread
{
public static void main(String[] args)
{
new NewThread();
try

multithreading in java 5
{
for(int i=5; i>0; i—)
{
[Link](”Main thread: “+i);
[Link](500);
}
}
catch(InterruptedException e)
{
[Link](”Main thread
interrupted”);
}
[Link](”main thread exiting”);
}
}

super() inside NewThread invokes the Thread


constructor public Thread(String
threadName)

multithreading in java 6

Common questions

Powered by AI

Java ensures efficient inter-thread communication by allowing threads within the same process to share memory space, which facilitates easy and rapid data exchange. This approach is less costly and complex compared to interprocess communication, which requires more resources and is limited due to the need for processes to exist in separate memory spaces. Inter-thread communication is achieved through synchronized methods and objects provided by Java, which ensure safe interaction between threads. This efficiency and reduced overhead make thread-based multitasking preferred over process-based multitasking when interacting within the same program .

Thread priorities in Java multithreading influence the scheduling of threads by determining the order in which threads are executed. Threads with higher priority are more likely to be selected for execution by the thread scheduler compared to lower-priority threads. A lower-priority thread may be preempted if a higher-priority thread becomes ready to run. This preemptive multitasking ensures that critical tasks are performed promptly .

When using the Runnable interface in Java, a thread is started by first creating a class that implements Runnable and defines the run() method, which contains the code to be executed by the thread. An instance of this class is created, and a Thread object is associated with it by passing the Runnable instance as a parameter to the Thread constructor. The start() method of the Thread object is then called, which in turn invokes the run() method to start the thread execution .

The inexpensive nature of context switching in thread-based multitasking implies that switching between threads within the same process incurs minimal overhead and can be done quickly. This is because threads share the same address space and do not require the extensive resource allocation needed for process context switching, which involves more complex memory management. Consequently, this allows for more responsive multitasking and efficient CPU usage, as more threads can be switched and executed in a shorter time. It also contributes to the overall scalability of applications, enabling them to handle more concurrent operations smoothly .

The main thread in a Java program is the initial thread that starts executing when a Java program begins. It executes the main() method and is responsible for spawning child threads if needed. Unlike child threads, the main thread typically completes its execution only after all child threads have finished, thereby allowing for orderly shutdown activities. Child threads, on the other hand, are spawned from the main thread and execute concurrently, performing various tasks independently, though still under the control of the Java runtime .

To create and start a new thread by extending the Thread class in Java, a class should extend Thread and override the run() method, which contains the code to be executed by the thread. In the subclass's constructor, super() is called to invoke the Thread constructor, which initializes thread properties. The start() method is called within the constructor to begin thread execution, invoking the run() method. For example: class NewThread extends Thread { NewThread() { super("Demo Thread"); System.out.println("Child thread: " + this); start(); // Start the thread } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } In the main class, an instance of NewThread is created, launching the thread: class ExtendThread { public static void main(String[] args) { new NewThread(); try { for (int i = 5; i > 0; i--) { System.out.println("Main thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } System.out.println("Main thread exiting"); } }.

In Java, process-based multitasking involves running two or more programs concurrently, which tends to be heavier because each process requires its own address space. Context switching between processes is more expensive, and interprocess communication is costly and limited. Conversely, thread-based multitasking involves performing multiple tasks within a single program using threads, which share the same address space. This approach is lighter because context switching is inexpensive and inter-thread communication is efficient. Thread-based multitasking is under Java's control, whereas process-based multitasking is not .

In Java, multithreading can be implemented using two main approaches: implementing the Runnable interface and extending the Thread class. When implementing the Runnable interface, a class must implement the run() method, which contains the code to be executed by the thread. This method establishes an entry point for the new thread. An instance of Thread must be created within the class that implements Runnable, passing the Runnable instance to it, and start() must be called to begin execution. When extending the Thread class, the extending class must override the run() method and call the start() method to begin execution .

In Java, thread priorities determine which thread gets CPU access when multiple threads are runnable. The threads with higher priorities are more likely to be executed first. Context switching occurs when a thread voluntarily relinquishes control by yielding, sleeping, or blocking. A lower priority thread will be preempted by a higher priority one if it does not voluntarily yield the processor. This process is known as preemptive multitasking .

Multithreading in Java is considered more efficient than single-threaded execution because it allows multiple parts of a program to run concurrently, which keeps the CPU idle time to a minimum. This approach enables better resource utilization and responsiveness, as threads can perform various tasks simultaneously, unlike single-threaded execution, which processes tasks sequentially .

You might also like