forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistributedCircularListSum.java
107 lines (93 loc) · 1.64 KB
/
DistributedCircularListSum.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
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
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/03/distributed-circular-linked-list-sum.html
*/
package com.dsalgo;
class DistributedCircularListSum
{
public static volatile boolean startFlag = false;
private static Boolean flag = false;
public static void main(String[] args)
{
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
Node d = new Node(4);
Node e = new Node(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
e.next = a;
startFlag = true;
}
private static class Node
{
Node next;
int value;
Integer data;
public Node(int value)
{
this.value = value;
new Thread(new NodeRunner(this, value)).start();
}
public synchronized void send(int data)
{
this.data = data;
}
}
private static class NodeRunner implements Runnable
{
Node node;
int id;
public NodeRunner(Node node, int id)
{
this.node = node;
this.id = id;
}
@Override
public void run()
{
while (!startFlag)
{
}
boolean isFirst = false;
synchronized (flag)
{
if (flag == false)
{
flag = true;
isFirst = true;
}
}
if (isFirst)
node.next.send(node.value);
else
{
while (node.data == null)
{
try
{
Thread.sleep(10);
} catch (InterruptedException e)
{
}
}
int sum = node.value + node.data;
node.data = null;
node.next.send(sum);
}
while (node.data == null)
{
try
{
Thread.sleep(10);
} catch (InterruptedException e)
{
}
}
System.out.println("id:" + id + "sum:" + node.data);
node.next.send(node.data);
}
}
}