-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMeetUpEventSimulator.java
More file actions
93 lines (78 loc) · 2.66 KB
/
Copy pathMeetUpEventSimulator.java
File metadata and controls
93 lines (78 loc) · 2.66 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class MeetUpEventSimulator {
public static class MeetUpEvent{
private String eventName;
private AtomicLong guestCount = new AtomicLong(1);//1 for organiser
public MeetUpEvent(String eventName){
this.eventName = eventName;
}
public void attending(int count){
if(count == 1){
guestCount.incrementAndGet();
}
else{
guestCount.addAndGet(count);
}
}
public void nonAttending(int count){
if(count == 1){
guestCount.decrementAndGet();
}
else{
boolean updated = false;
while(!updated) {
long currentGuestCount = guestCount.get();
long newGuestCount = currentGuestCount - count;
updated = guestCount.compareAndSet(currentGuestCount,newGuestCount);
}
}
}
public long getCount(){
return guestCount.get();
}
}
public static void main(String[] args) {
MeetUpEvent jugBoston = new MeetUpEvent("The Boston Java User group");
Thread user1 = new Thread(new Runnable() {
@Override
public void run() {
jugBoston.attending(4);
System.out.println(Thread.currentThread().getName()+":"+jugBoston.getCount());
}
});
Thread user2 = new Thread(new Runnable() {
@Override
public void run() {
jugBoston.attending(3);
System.out.println(Thread.currentThread().getName()+":"+jugBoston.getCount());
jugBoston.nonAttending(3);
System.out.println(Thread.currentThread().getName()+":"+jugBoston.getCount());
}
});
Thread user3 = new Thread(new Runnable() {
@Override
public void run() {
jugBoston.attending(1);
System.out.println(Thread.currentThread().getName()+":"+jugBoston.getCount());
}
});
user1.setName("user1");
user2.setName("user2");
user3.setName("user3");
user1.start();
sleep(1);
user2.start();
sleep(2);
user3.start();
sleep(2);
System.out.println("The total user count is :"+jugBoston.getCount());
}
public static void sleep(int i){
try {
TimeUnit.SECONDS.sleep(i);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}