-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadEx5.java
More file actions
64 lines (54 loc) · 1.71 KB
/
ThreadEx5.java
File metadata and controls
64 lines (54 loc) · 1.71 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
// Thread Safe
// only one thread can work on a thing at a time!
// Avoid instability and race conditions in code!
class Counter{
int count=0;
//synchronized - makes it to be called by one thread at a time!
public synchronized void increment(){ // 'synchronized' makes only one thread access this method at a time!
// This avoids race condition and makes desired output!
count++; // read, increment, store in memory!
//count = count + 1; (get + update)!
}
}
public class ThreadEx5{
public static void main(String args[]){
Counter c = new Counter();
//Runnable Objects
//Using Anonymous class!
Runnable objA = new Runnable(){ // instantiate an Interface with anonymous class!
public void run(){
for(int i=1;i<=1000;i++){
c.increment();
}
}
};
//Using Lambda Function (Works only for Functional Interface!)
Runnable objB = () ->
{
for(int i=1;i<=1000;i++){
c.increment();
}
};
//Create Threads manually
Thread t1 = new Thread(objA); //NEW STATE
Thread t2 = new Thread(objB); //NEW STATE
//Trigger the Threads!
t1.start(); //RUNNING(got cpu) & RUNNABLE(waiting for scheduler to get cpu)
t2.start(); //RUNNING(got cpu) & RUNNABLE(waiting for scheduler to get cpu)
//NOTE
//Using sleep() or wait() on threads makes it to go WAITING STATE!
//notify() -> waiting to runnable
//stop() -> running/runnable to terminate
//make a wait till both threads complete the task!
//makes main thread to wait for t1,t2 threads!
try{
t1.join(); //ask main thread to wait for this threads to terminate!
t2.join();
}
catch(InterruptedException e){
System.out.println(e);
}
//all jobs are done, finally check value of count!
System.out.println(c.count);
}
}