-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelloThreadsWait.java
More file actions
57 lines (44 loc) · 1.11 KB
/
HelloThreadsWait.java
File metadata and controls
57 lines (44 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
Java Threads Hello, World! with joins
@author Jim Teresco
@version Fall 2021
*/
public class HelloThreadsWait {
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Usage: Java HelloThreads numThreads");
System.exit(1);
}
// how many threads?
int n = Integer.parseInt(args[0]);
if (n < 1) {
System.err.println("Must specify number of threads");
System.exit(1);
}
// an array of Thread references so we can wait for them
// to finish
Thread threads[] = new Thread[n];
// construct the correct number of threads, overriding its run
// method with the code we want the thread to execute and
// calling its start method to launch the thread
for (int i = 0; i < n; i++) {
threads[i] = new Thread() {
@Override
public void run() {
System.out.println("Hello from thread!");
}
};
threads[i].start();
}
// wait for each to finish
for (int i = 0; i < n; i++) {
try {
threads[i].join();
}
catch (InterruptedException e) {
System.err.println(e);
}
}
System.out.println("End of main");
}
}