-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex.java
66 lines (62 loc) · 2.18 KB
/
mutex.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
package SPOS;
public class mutex {
public final static int NUMTHREADS = 3;
public static int sharedData = 0;
public static int sharedData2 = 0;
static class theLock extends Object{
}
static public theLock lockObject = new theLock();
static class theThread extends Thread
{
public void run()
{
System.out.print("Thread " + getName() + ": Entered\n");
synchronized (lockObject)
{
/********** Critical Section *******************/
System.out.println("Thread " + getName() + ": Start critical section, in synchronized block\n");
++sharedData;
--sharedData2;
System.out.print("Thread " + getName() + ": End critical section, leave synchronized block\n");
/********** Critical Section *******************/
}
}
}
public static void main(String argv[]) {
theThread threads[] = new theThread[NUMTHREADS];
System.out.print("Entered the testcase\n");
System.out.print("Synchronize to prevent access to shared data\n");
synchronized (lockObject)
{
System.out.print("Create/start the thread\n");
for (int i = 0; i < NUMTHREADS; ++i)
{
threads[i] = new theThread();
threads[i].start();
}
System.out.print("Wait a bit until we're 'done' with the shared data\n");
try
{
Thread.sleep(3000);
}
catch (InterruptedException e){
System.out.print("sleep interrupted\n");
}
System.out.print("Unlock shared data\n");
}
System.out.print("Wait for the threads to complete\n");
try
{
for (int i = 0; i < NUMTHREADS; ++i)
{
threads[i].join();
System.out.print("Testcase completed\n");
System.exit(0);
}
}
catch (InterruptedException e)
{
System.out.print("Join interrupted\n");
}
}
}