-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChildCareSolution_Unsynchronized1.java
More file actions
118 lines (84 loc) · 2.73 KB
/
ChildCareSolution_Unsynchronized1.java
File metadata and controls
118 lines (84 loc) · 2.73 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mk.ukim.finki.os.synchronization.problems.ChildCare;
import mk.ukim.finki.os.synchronization.ProblemExecution;
import mk.ukim.finki.os.synchronization.TemplateThread;
import java.util.HashSet;
import java.util.concurrent.Semaphore;
/**
*
* @author Nikolina
*/
// Несинхронизирано решение - deadlocks при излегувањето на воспитувачите и влегувањето на децата.
public class ChildCareSolution_Unsynchronized1 {
public static Semaphore multiplex;
public static void init()
{
multiplex = new Semaphore(3);
}
public static class Adult extends TemplateThread
{
public Adult(int numberOfRuns)
{
super(numberOfRuns);
}
@Override
public void execute() throws InterruptedException {
// Adult entering.
state.adultEntered();
multiplex.release(3);
// Critical region.
// Adult leaving.
state.adultLeaving();
state.adultLeft();
multiplex.acquire();
multiplex.acquire();
multiplex.acquire();
}
}
public static class Child extends TemplateThread
{
public Child(int numberOfRuns)
{
super(numberOfRuns);
}
@Override
public void execute() throws InterruptedException {
// Child entering.
state.childEntering();
state.childrenEntered(1);
multiplex.acquire();
// Critical region.
// Child leaving.
state.childLeft();
multiplex.release();
}
}
static ChildCareState state = new ChildCareState();
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("Run: " + i);
run();
}
}
public static void run() {
try {
int numChildren = 100;
HashSet<Thread> threads = new HashSet<>();
ChildCareSolution_Unsynchronized1.Adult adult = new ChildCareSolution_Unsynchronized1.Adult((numChildren / 3) + 1);
threads.add(adult);
int numRuns = 1;
for (int i = 0; i < numChildren; i++) {
ChildCareSolution_Unsynchronized1.Child child = new ChildCareSolution_Unsynchronized1.Child(numRuns);
threads.add(child);
}
init();
ProblemExecution.start(threads, state);
} catch (Exception e) {
e.printStackTrace();
}
}
}