Reading and writing in the array using threads
Last Updated :
17 Mar, 2023
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). Arrays are used to store homogeneous data. The conventional way of storing the elements in an array and reading the elements from an array takes a lot of time if there are numerous elements.

Writing and reading elements in an array is a small problem where each element is first added to the array and then the entire array is read element by element and printed on the console. But when the number of elements is too large, it could take a lot of time. But this could be solved by dividing the writing and reading tasks into parts.
This could be done by using multi-threading where each core of the processor is used. In this case, two threads are used, where one thread is responsible for writing to the array and the other thread is responsible for reading the array. In this way, the performance of a program can be improved as well as the cores of the processor can be utilized. It is better to use one thread for each core. Although one can create as many threads as required for a better understanding of multi-threading.
This article focuses on writing and reading the elements of the array using the concept of multithreading.
Approach: This section states the algorithm that is followed to design a program to writing and read elements of an array using multithreading:
- In the first step, two threads will be created.
- One for writing operation and one for reading operation.
- Here the synchronized keyword is used with the array so that only one thread can access the array at a time.
- First, the write operation will be performed on the array.
- Then, the read operation is performed on the array.
Below is the Java program to implement the above approach-
C++14
#include <iostream>
#include <thread>
using namespace std;
int main()
{
// Array created for 5 elements
int a[5];
// Thread created for write operation
thread t1([]() {
// Here the array is being
// synchronized
lock_guard<mutex> lock(m);
cout << "Enter the elements : " << endl;
for (int i = 0; i < 5; i++) {
cin >> a[i];
}
cout << "Writing done Successfully" << endl;
});
// Thread created for read operation
thread t2([]() {
// Here the array is being
// synchronized
lock_guard<mutex> lock(m);
cout << "The elements are : " << endl;
for (int i = 0; i < 5; i++) {
cout << a[i] << endl;
}
cout << "Reading done successfully" << endl;
});
// Write thread is started
t1.join();
// Read thread is started
t2.join();
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Array created for 5 elements
int a[] = new int[5];
// Thread created for write operation
Thread t1 = new Thread(new Runnable() {
public void run()
{
// Here the array is being
// synchronized
synchronized (a)
{
Scanner s = new Scanner(System.in);
System.out.println(
"Enter the elements : ");
for (int i = 0; i < 5; i++) {
a[i] = s.nextInt();
}
System.out.println(
"Writing done Successfully");
}
}
});
// Thread created for read operation
Thread t2 = new Thread(new Runnable() {
public void run()
{
// Here the array is being
// synchronized
synchronized (a)
{
System.out.println(
"The elements are : ");
for (int i = 0; i < 5; i++) {
System.out.println(a[i]);
}
System.out.println(
"Reading done successfully");
}
}
});
// Write thread is started
t1.start();
// Read thread is started
t2.start();
}
}
Python3
import threading
# Array created for 5 elements
a = [0] * 5
# Lock object to synchronize access to the array
lock = threading.Lock()
# Thread created for write operation
t1 = threading.Thread(target=lambda: write_thread())
# Thread created for read operation
t2 = threading.Thread(target=lambda: read_thread())
def write_thread():
global a
global lock
# Here the array is being synchronized
with lock:
print("Enter the elements:")
for i in range(5):
a[i] = int(input())
print("Writing done successfully")
def read_thread():
global a
global lock
# Here the array is being synchronized
with lock:
print("The elements are:")
for i in range(5):
print(a[i])
print("Reading done successfully")
# Write thread is started
t1.start()
# Read thread is started
t2.start()
# Wait for both threads to finish
t1.join()
t2.join()
# This code is contributed by akashish__
C#
// C# program for the above approach
using System;
using System.Threading;
public class GFG
{
static public void Main()
{
// Array created for 5 elements
int[] a = new int[5];
// Thread created for write operation
Thread t1 = new Thread(() => {
// Here the array is being
// synchronized
lock(a) {
Console.WriteLine("Enter the elements : ");
for (int i = 0; i < 5; i++) {
a[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Writing done Successfully");
}
});
// Thread created for read operation
Thread t2 = new Thread(() => {
// Here the array is being
// synchronized
lock(a) {
Console.WriteLine("The elements are : ");
for (int i = 0; i < 5; i++) {
Console.WriteLine(a[i]);
}
Console.WriteLine("Reading done successfully");
}
});
// Write thread is started
t1.Start();
// Read thread is started
t2.Start();
}
}
// This code is contributed by akashish__
JavaScript
// Array created for 5 elements
let a = new Array(5);
// Thread created for write operation
let t1 = new Thread(() => {
// Here the array is being
// synchronized
lock_guard.lock(m);
console.log("Enter the elements : ");
for (let i = 0; i < 5; i++) {
a[i] = prompt();
}
console.log("Writing done Successfully");
});
// Thread created for read operation
let t2 = new Thread(() => {
// Here the array is being
// synchronized
lock_guard.lock(m);
console.log("The elements are : ");
for (let i = 0; i < 5; i++) {
console.log(a[i]);
}
console.log("Reading done successfully");
});
// Write thread is started
t1.start();
// Read thread is started
t2.start();
// This code is contributed by akashish__
Output:

Explanation: Here, firstly the write thread is started and at that time read thread will not interfere as the array is synchronized. Similarly, during reading, write thread will not interfere.
Similar Reads
How to Copy a File in Multiple Threads Using Java?
Copying files is a task, in programming that deals with file manipulation. Although Java offers tools, for file handling copying files can slow down our application's performance. To optimize this process, we can take advantage of multithreading, which enables threads to work on various sections of
3 min read
Understanding threads on Producer Consumer Problem | Java
Thread is a part of execution i.e., it is an independent path of execution in a program. A program can have more than one thread which rises the concept of multithreading. We must use java.lang.Thread class in order to use a thread to perform a specific task. In this article, let's see the implement
10 min read
How to Find Prime and Palindrome Numbers using Multi-Threading in Java?
Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Multiple threads don't
4 min read
Print even and odd numbers in increasing order using two threads in Java
Given an integer N, the task is to write Java Program to print the first N natural numbers in increasing order using two threads.Prerequisite: MultithreadingExamples:Input: N = 10Output: 1 2 3 4 5 6 7 8 9 10Input: N = 18Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18Approach: The idea is to cre
3 min read
How to Implement a Thread-Safe Resizable Array in Java?
Multiple threads may securely execute operations like insertion and deletion without risking data corruption when utilizing a thread-safe resizable array. The ArrayList class is a popular Java class, yet it is not thread-safe by default. We may use concurrent collections or synchronization to make i
2 min read
How to make ArrayList Thread-Safe in Java?
In Java, Thread is the smallest unit of execution within the program. It represents an independent path of execution that can run concurrently with other threads. When dealing with multi-threaded applications, where multiple threads are accessing and modifying data concurrently, it's crucial to ensu
3 min read
How to Perform Parallel Processing on Arrays in Java Using Streams?
In Java, parallel processing helps to increase overall performance. Arrays may be processed in parallel in Java by using Streams API. When working with big datasets or computationally demanding tasks, this is very helpful. In this article, we will learn how to perform parallel processing on arrays i
2 min read
Create Thread-safe HashMap Without Using Collections.synchronizedMap in Java
The HashMap class in Java is a commonly used data structure for storing key-value pairs. While HashMap provides fast and efficient operations, it is not inherently thread-safe. When working in a multi-threaded environment, it's crucial to ensure that data structures are accessed and modified in a wa
4 min read
How to Display all Threads Status in Java?
Threads are light-weight processes within a process.. Multithreading in java is a feature that allows concurrent execution of two or more parts of a program to maximize the utilization of CPU. here the approach to retrieve the state of the thread is via getState() method of the Thread class. A java
2 min read
Java Threading Programs - Basic to Advanced
Java threading is the concept of using multiple threads to execute different tasks in a Java program. A thread is a lightweight sub-process that runs within a process and shares the same memory space and resources. Threads can improve the performance and responsiveness of a program by allowing paral
3 min read