You are on page 1of 3

PRACTICAL EXAM ANSWER-SHEET

Enrollment Number: EC2332251010489 Name of student: Tushar Chaudhary

Date:11-07-2023 Subject Code: V20PCA101

Name of Subject: Programming Using Java

Title: Demonstrate the concept of Threads to achieve multitasking program using


Thread class and Runnable Interface.
Aim:
Create an Array of 9 numbers. And create three Threads to split the task evenly
among the three threads. And each thread has to add up and report the answer to the
main thread where the main thread waits for the 3 threads and computes the
summation of all the three threads. Note: Assign names to the threads as well.
Procedure/Steps:

1. Start the Program.


2. Use thread class.
3. Import u l java package.

4. Throws Interrupted Excep on.

5. Take numbers and chunk size as variable name.

6. Use Runnable Interface also.

7. Execute the program and print the result.

8. Stop the Program.


Program:

class NumberThread extends Thread {

private int[] numbers;

private int startIndex;

private int endIndex;

private int sum;

public NumberThread(int[] numbers, int startIndex, int endIndex) {


this.numbers = numbers;
this.startIndex = startIndex;

ti

ti

this.endIndex = endIndex;

this.sum = 0;

@Override

public void run() {

for (int i = startIndex; i <= endIndex; i++) {

sum += numbers[i];

System.out.println(Thread.currentThread().getName() + ": " + sum);

public int getSum() {

return sum;

public class sum {

public sta c void main(String[] args) {

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int startIndex = 0;

int endIndex = 2;

int totalSum = 0;

NumberThread thread1 = new NumberThread(numbers, startIndex, endIndex);

NumberThread thread2 = new NumberThread(numbers, startIndex + 3, endIndex + 3);

NumberThread thread3 = new NumberThread(numbers, startIndex + 6, endIndex + 6);

thread1.start();

thread2.start();

thread3.start();

ti

try {

thread1.join();

thread2.join();

thread3.join();

} catch (InterruptedExcep on e) {
e.printStackTrace();
}

totalSum = thread1.getSum() + thread2.getSum() +


thread3.getSum(); System.out.println("Total Sum: " + totalSum);
}

Result/Output:

Result:

successfully executed

ti

You might also like