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

Multithreading in Java -1

Uploaded by

luvyakapoor22
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)
7 views6 pages

Multithreading in Java -1

Uploaded by

luvyakapoor22
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
You are on page 1/ 6

Multithreading in Java

What is multithreading- The Java programming concept known as multithreading enables several threads to
operate simultaneously inside just one application. The smallest computational unit that the system's operating
system can schedule is a thread, which is an extremely lightweight subprocess. Java's support for multithreading
makes it possible to manage several threads within of a single application, which is especially useful for
processing activities concurrently, conserving resource usage, and boosting app performance.
How to Create Threads in Java-The thread is created in following ways
1. Extending the Thread class: The example is given as following
class MCA extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}

public class BTECH {


public static void main(String[] args) {
Thread t1 = new Thread();
t1.start (); // Starts the thread
}
}
2. Implementing the Runnable interface: The example is given as following
class MCA implements Runnable {
public void run() {
System.out.println("This is MCA...");
}
}

public class BTECH {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
Thread Life Cycle-
 New: Although a thread is created, it is not activated.
 Runnable: Awaiting CPU, eager to run.
 Running: Performing actively.
 Blocked/Waiting: Waiting for another thread, you paused.
 Terminated: The execution is complete.
The following diagram for thread life cycle is given as following:-
Extending Thread Class- One may additionally extend the Thread class or implement the Runnable interface
in Java to create a new thread. Developers can specify the code that they should be launch when the thread
begins running by overriding the run() function's parameters if you choose to extend the Thread class.
This is a simple instance that shows how to extend the Thread class:
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}

public class Main {


public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();

thread1.start();
thread2.start();
System.out.println("Main thread finished.");
}
}
Output-
Main thread finished.
Thread-0 - Count: 1
Thread-1 - Count: 1
Thread-0 - Count: 2
Thread-1 - Count: 2
Thread-0 - Count: 3
Thread-1 - Count: 3
Thread-0 - Count: 4
Thread-1 - Count: 4
Thread-0 - Count: 5
Thread-1 - Count: 5
Essential Points:
 The thread's execution is started using the start() method. It calls the run() method within it.
 The code which will be run in the new thread is included in the run() method.
 Because Java does not provide multiple inheritance capabilities, extending the Thread class will be
simpler but not more flexible than implementing the Runnable interface.

Runnable Interface:- In Java, an operation or amount of task that can be completed by a thread is denoted by
the Runnable interface, an interface with functions. run(), the only method it has, is called when the thread starts
and is part of the java.lang package

Characteristics of Runnable:

 Separation of Concerns: Runnable improves simpler design by enabling you differentiate the task (the
code to run) from the thread that takes it out.
 Reusability: Runnable examples that can be consumed by multiple threads can be created.
 Variability: Various strands can be generated to handle the same runnable task at the same time.
Key Points about Runnable Interface:
a) Operational Connection: The Runnable interface is a constructive interface since it only has one abstract
method, run(). It therefore makes it possible to use lambda expressions to create instances of Runnable.
b)Method Definition:
public interface Runnable {
void run();
}
c) Two methods are available for implementing the Runnable interface:
 By overriding the run() function in a class which implements Runnable.
 By the use of a lambda expression (which is primarily in Java 8 and later).
The example is given as following-
public class MCA implements Runnable {
public void run() {
System.out.println("MCA Class is running in a thread.");
}
}
To execute this task in a thread:
public class BTECH {
public static void main(String[] args) {
MCA m = new MCA();
Thread t1 = new Thread(myRunnable);
t1.start(); // Starts the thread and executes the run() method
}
}
d) Starting a Thread: You can start a Runnable task in a new thread by passing it to a Thread object. This is
how to go about it:
Example of Using Runnable
class MCA implements Runnable {
public void run() {
System.out.println("MCA Class is running...");
}
}
public class BTECH {
public static void main(String[] args) {
MCA m = new MCA();
Thread t1 = new Thread(task);
t1.start();
}
}
Using a Lambda Expression

public class MyLambda {


public static void main(String[] args) {
Runnable task = () -> System.out.println("Thread running using Lambda!");

Thread t1 = new Thread(task);


t1.start();
}
}

Thread Synchronization
In Java, thread synchronisation is a process that ensure that two or more running threads can safely access
shared resources without corrupting or providing unreliable information. In multi-threaded applications,
where several threads could try how to read or write to shared elements at comparable time, this is particularly
critical.
Synchronized Methods
You can declare a method as synchronized to ensure that only one thread can execute it at a time for a given
instance of the class.
public class sync {
private int count = 0;

public synchronized void increment() {


count++;
}

public synchronized int getCount() {


return count;
}
}
Synchronized Blocks- The ability to synchronise a section of code inside a method instead of coordinating the
full method. This enables accurate synchronisation control.
Example-
public class sync {
private int count = 0;
private final Object lock = new Object();

public void increment() {


synchronized (lock) {
count++;
}
}

public int getCount() {


synchronized (lock) {
return count;
}
}
}
Static Synchronization-Static synchronisation ensures that all instances share the exact identical lock by
locking the class object rather than an oneself instance.
class SharedStatic {
static synchronized void display(String message) {
System.out.print("[ " + message);
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println(" ]");
}
}
Volatile Keyword-All threads can see changes made to a property thanks to the volatile keyword. It ensures
visibility but fails to offer atomic structure.
public class SharedObject {
private volatile boolean flag = false;

public void setFlag(boolean flag) {


this.flag = flag;
}

public boolean isFlag() {


return flag;
}
}
Points to remember
 Cut Down on Synchronisation Scope: To decrease needless performance overhead, only synchronise the most
essential code fragments.
 Prevent Deadlocks: To avoid deadlocks, make certain that the locks are acquired in an ongoing order.
 Adopt High-Level Concurrency is Utilities: Each time feasible, use classes from java.util.concurrent against
low-level synchronisation schemes.
 Immutable Objects: To prevent synchronisation problems, use immutable objects whenever you can.

You might also like