-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultithread.java
More file actions
54 lines (34 loc) · 1.19 KB
/
multithread.java
File metadata and controls
54 lines (34 loc) · 1.19 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
class sharedVariables {
public int shared_variable;
}
// Java code for thread creation by extending
// the Thread class
class multithreadingDemo extends Thread {
private sharedVariables objSharedVar;
public multithreadingDemo (sharedVariables _objSharedVar) {
objSharedVar = _objSharedVar;
}
public void run() {
try {
// Displaying the thread that is running
//System.out.println ("Thread " + Thread.currentThread().getId() + " is running");
System.out.println ("Thread id: "+Thread.currentThread().getId()+" and value is: "+objSharedVar.shared_variable);
objSharedVar.shared_variable++;
} catch (Exception e) {
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
public class multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
sharedVariables objSharedVar = new sharedVariables();
objSharedVar.shared_variable = 0;
for (int i = 0; i < 8; i++) {
multithreadingDemo object = new multithreadingDemo(objSharedVar);
object.start();
}
}
}