Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
66 views

Multithreading in Java

Multithreading in Java allows executing multiple threads simultaneously by using lightweight subprocesses called threads that can achieve multitasking. Threads share a memory area to save memory compared to processes and have faster context switching. There are two primary mechanisms for creating threads - extending the Thread class or implementing the Runnable interface. Synchronization is used to coordinate thread access to shared resources to avoid erroneous results and ensure only one thread can access a resource at a time through synchronized blocks or methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Multithreading in Java

Multithreading in Java allows executing multiple threads simultaneously by using lightweight subprocesses called threads that can achieve multitasking. Threads share a memory area to save memory compared to processes and have faster context switching. There are two primary mechanisms for creating threads - extending the Thread class or implementing the Runnable interface. Synchronization is used to coordinate thread access to shared resources to avoid erroneous results and ensure only one thread can access a resource at a time through synchronized blocks or methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Multithreading in Java

• Multithreading in Java 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.

• A thread is a lightweight subprocess, 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.
• Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
• Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class
overrides the run() method available in the Thread class. A thread
begins its life inside run() method. We create an object of our new class
and call start() method to start the execution of a thread. Start() invokes
the run() method on the Thread object.

• Java

// Java code for thread creation by extending


// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}

• Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface
and override run() method. Then we instantiate a Thread object and call
start() method on this object.

• Java

// Java code for thread creation by implementing


// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}

Synchronization in Java
• Multi-threaded programs may often come to a situation where
multiple threads try to access the same resources and finally produce
erroneous and unforeseen results.
• Java Synchronization is used to make sure by some synchronization
method that only one thread can access the resource at a given point
in time.

• Java provides a way of creating threads and synchronizing their tasks


using synchronized blocks.
• A synchronized block in Java is synchronized on some object. All
synchronized blocks synchronize on the same object and can only have
one thread executed inside them at a time. All other threads attempting
to enter the synchronized block are blocked until the thread inside the
synchronized block exits the block.

• General Form of Synchronized Block

// Only one thread can execute at a time.


// sync_object is a reference to an object
// whose lock associates with the monitor.
// The code is said to be synchronized on
// the monitor object
synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
This synchronization is implemented in Java with a concept called monitors
or locks. Only one thread can own a monitor at a given time. When a thread
acquires a lock, it is said to have entered the monitor. All other threads
attempting to enter the locked monitor will be suspended until the first
thread exits the monitor.

• Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization

1. Process Synchronization in Java

Process Synchronization is a technique used to coordinate the execution of


multiple processes. It ensures that the shared resources are safe and in order.
2. Thread Synchronization in Java

Thread Synchronization is used to coordinate and ordering of the execution


of the threads in a multi-threaded program. There are two types of thread
synchronization are mentioned below:
• Mutual Exclusive
• Cooperation (Inter-thread communication in Java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while
sharing data. There are three types of Mutual Exclusive mentioned below:
• Synchronized method.
• Synchronized block.
• Static synchronization.

Life cycle of a Thread (Thread States)


• https://www.javatpoint.com/life-cycle-of-a-thread
• https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/

Volatile Keyword in Java


Volatile keyword is used to modify the value of a variable by different threads. It is also
used to make classes thread safe. It means that multiple threads can use a method and
instance of the classes at the same time without any problem. The volatile keyword
can be used either with primitive type or objects.

The volatile keyword does not cache the value of the variable and always read the
variable from the main memory. The volatile keyword cannot be used with classes or
methods. However, it is used with variables. It also guarantees visibility and ordering.
It prevents the compiler from the reordering of code.

The contents of the particular device register could change at any time, so you need
the volatile keyword to ensure that such accesses are not optimized away by the
compiler.

o You can use a volatile variable if you want to read and write long and double
variable automatically.
o It can be used as an alternative way of achieving synchronization in Java.
o All reader threads will see the updated value of the volatile variable after
completing the write operation. If you are not using the volatile keyword,
different reader thread may see different values.
o It is used to inform the compiler that multiple threads will access a particular
statement. It prevents the compiler from doing any reordering or any
optimization.
o If you do not use volatile variable compiler can reorder the code, free to write
in cache value of volatile variable instead of reading from the main memory.

Understanding the problem without


Synchronization
In this example, there is no synchronization, so output is inconsistent. Let's see the
example:

TestSynchronization1.java

1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. }
9.
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. }
21.
22. }
23. class MyThread2 extends Thread{
24. Table t;
25. MyThread2(Table t){
26. this.t=t;
27. }
28. public void run(){
29. t.printTable(100);
30. }
31. }
32.
33. class TestSynchronization1{
34. public static void main(String args[]){
35. Table obj = new Table();//only one object
36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
39. t2.start();
40. }
41. }
Output:

5
100
10
200
15
300
20
400
25
500

Java Synchronized Method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

TestSynchronization2.java

1. //example of java synchronized method


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }

Output:

5
10
15
20
25
100
200
300
400
500

You might also like