129k views
0 votes
Write a program that launches 1000 threads. Each thread adds 1 to a variable sum that initially is 0 (zero).

1 Answer

5 votes

Answer:

The answer is below

Step-by-step explanation:

Using Java programming language.

*//we have the following codes//*

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class My_Answer {

private static Integer sum = 0;

public static void main(String[] args) {

ExecutorService executor = Executors.newCachedThreadPool();

for (int i = 0; i < 1000; i++) {

executor.execute(new AddOne());

}

executor.shutdown();

while (!executor.isTerminated()) {

}

System.out.println("sum = " + sum);

}

private static class Add_Extra implements Runnable {

public void run() {

sum++;

}

}

}

User Thant Sin Aung
by
5.0k points