Datasets:
ArXiv:
License:
Stack-Repo
/
data
/train
/akash-coded
/FSD_Java
/Lesson-3
/Concurrency and Multithreading
/Examples
/MultipleThreadsDemo.java
| import java.util.ArrayList; | |
| import java.util.List; | |
| public class MultipleThreadsDemo { | |
| public static void main(String[] args) { | |
| // We will store the threads so that we can check if they are done | |
| List<Thread> threads = new ArrayList<>(); | |
| // We will create 50 threads | |
| for (int i = 0; i < 50; i++) { | |
| Runnable task = new FindSumOfNumbers(10000000L + i); | |
| // ? Identify the Java concepts used in the above line | |
| Thread worker = new Thread(task); | |
| // We can set the name of the thread | |
| worker.setName(String.valueOf(i)); | |
| // Start the thread, never call method run() direct | |
| worker.start(); | |
| // Remember the thread for later usage | |
| threads.add(worker); | |
| } | |
| int running = 0; | |
| do { | |
| running = 0; | |
| for (Thread thread : threads) { | |
| if (thread.isAlive()) { | |
| running++; | |
| } | |
| } | |
| System.out.println("We have " + running + " running threads. "); | |
| } while (running > 0); | |
| } | |
| } | |