Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelloThreadsNumbered.java
More file actions
Latest commit
71 lines (54 loc) · 1.49 KB
/
Copy pathHelloThreadsNumbered.java
File metadata and controls
71 lines (54 loc) · 1.49 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
Java Threads Hello, World! with joins and thread IDs
@author Jim Teresco
@version Fall 2021
*/
publicclassHelloThreadsNumbered {
publicstaticvoidmain(Stringargs[]) {
if (args.length != 1) {
System.err.println("Usage: Java HelloThreads numThreads");
System.exit(1);
}
// how many threads?
intn = 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
Threadthreads[] = newThread[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 (inti = 0; i < n; i++) {
// pass our loop index as the thread ID
threads[i] = newWorkerThread(i) {
@Override
publicvoidrun() {
// we have access to the threadId here
System.out.println("Hello from thread " + threadId + "!");
}
};
threads[i].start();
}
// wait for each to finish
for (inti = 0; i < n; i++) {
try {
threads[i].join();
}
catch (InterruptedExceptione) {
System.err.println(e);
}
}
System.out.println("End of main");
}
}
/* our WorkerThread, which just adds an instance variable
and a constructor to set it to the Thread class. */
classWorkerThreadextendsThread {
protectedintthreadId;
publicWorkerThread(intthreadId) {
this.threadId = threadId;
}
}