-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreads_03.java
66 lines (56 loc) · 1.81 KB
/
Threads_03.java
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
class A implements Runnable {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("hi");
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
class B implements Runnable { // instead of extending with thread class we implemented runnable interface
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("hello");
}
}
}
public class Threads_03 {
public static void main(String[] args) {
// Runnable vs Thread
// Runnable obj1 = new A();
Runnable obj1 = new Runnable() {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("hi");
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
}
}
};
// Runnable obj2 = new B();
Runnable obj2 = () -> {
for (int i = 1; i <= 10; i++) {
System.out.println("hello");
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
}
};
// obj1.start(); // by implementing runnable instead of Exetending thread, start
// will not work
// obj2.start();
// what we can do is
Thread t1 = new Thread(obj1);// creating a thread objects
Thread t2 = new Thread(obj2);// thread class constructor takes a runnable class object
t1.start();
t2.start();
}
}