Repository navigation
Expand file tree
/
Copy pathTest.java
More file actions
79 lines (74 loc) · 2.93 KB
/
Copy pathTest.java
File metadata and controls
79 lines (74 loc) · 2.93 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
72
73
74
75
76
77
78
79
/*
Two ways to do multi-threading:
1) Using thread class (in previous to previous video)
- Make classes extend Thread class
- Code whatever you want to be executed parallelly inside run method of class
- Call start method using the objects
2) Using Runnable interface (in previous video)
- Make classes implements Runnable interface
- Code whatever you want to be executed parallelly inside run method of class
- Create thread object by passing class object in Thread constructor
- Call start method using the objects of Thread class
3) Using lambda expressions (this video)
- Same as using runnable interface
- But since runnable interface is functional interface, this can be achieved using lambda expressions also
Lambda expressions:
- for reducing code length
- for making code more efficient
*/
public class Test {
public static void main(String[] args) {
/*
1) Using anonymous class:
Runnable obj1 = new Runnable() {
@Override
public void run() {
for(int i=0;i<5;i++) {
System.out.println("Hi");
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
}
}
};
Runnable obj2 = new Runnable() {
@Override
public void run() {
for(int i=0;i<5;i++) {
System.out.println("Hello");
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
}
}
};
2) Using lambda expression:
Runnable obj1 = () -> {
for(int i=0;i<5;i++) {
System.out.println("Hi");
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
}
}
};
Runnable obj2 = () -> {
for(int i=0;i<5;i++) {
System.out.println("Hello");
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
}
}
};
*/
// 3) Directly providing obj value in thread constructor
Thread t1 = new Thread(() -> {
for(int i=0;i<5;i++) {
System.out.println("Hi");
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
}
});
Thread t2 = new Thread(() -> {
for(int i=0;i<5;i++) {
System.out.println("Hello");
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
}
});
t1.start();
try { Thread.sleep(10); } catch (InterruptedException ignored) {}
t2.start();
}
}