File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/datastructures/queues
test/java/com/thealgorithms/datastructures/queues Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22
33public class ThreadSafeQueue <T > {
44
5- private static class Node <T > {
6- T data ;
7- Node <T > next ;
5+ private static class Node <T > {
6+ T data ;
7+ Node <T > next ;
88
9- Node (T data ) {
10- this .data = data ;
11- }
12- }
9+ Node (T data ) {
10+ this .data = data ;
11+ }
12+ }
1313
14- private Node <T > head ;
15- private Node <T > tail ;
14+ private Node <T > head ;
15+ private Node <T > tail ;
1616
17- public synchronized void enqueue (T data ) {
18- Node <T > newNode = new Node <>(data );
17+ public synchronized void enqueue (T data ) {
18+ Node <T > newNode = new Node <>(data );
1919
20- if (tail == null ) {
21- head = tail = newNode ;
22- return ;
23- }
20+ if (tail == null ) {
21+ head = tail = newNode ;
22+ return ;
23+ }
2424
25- tail .next = newNode ;
26- tail = newNode ;
27- }
25+ tail .next = newNode ;
26+ tail = newNode ;
27+ }
2828
29- public synchronized T dequeue () {
30- if (head == null ) {
31- return null ;
32- }
29+ public synchronized T dequeue () {
30+ if (head == null ) {
31+ return null ;
32+ }
3333
34- T data = head .data ;
35- head = head .next ;
34+ T data = head .data ;
35+ head = head .next ;
3636
37- if (head == null ) {
38- tail = null ;
39- }
37+ if (head == null ) {
38+ tail = null ;
39+ }
4040
41- return data ;
42- }
41+ return data ;
42+ }
4343
44- public synchronized boolean isEmpty () {
45- return head == null ;
46- }
44+ public synchronized boolean isEmpty () {
45+ return head == null ;
46+ }
4747}
Original file line number Diff line number Diff line change 22
33public class ThreadSafeQueueTest {
44
5- public static void main (String [] args ) {
5+ public static void main (String [] args ) {
66
7- ThreadSafeQueue <Integer > queue = new ThreadSafeQueue <>();
7+ ThreadSafeQueue <Integer > queue = new ThreadSafeQueue <>();
88
9- Thread producer = new Thread (() -> {
10- for (int i = 1 ; i <= 5 ; i ++) {
11- queue .enqueue (i );
12- System .out .println ("Enqueued: " + i );
13- }
14- });
9+ Thread producer = new Thread (() -> {
10+ for (int i = 1 ; i <= 5 ; i ++) {
11+ queue .enqueue (i );
12+ System .out .println ("Enqueued: " + i );
13+ }
14+ });
1515
16- Thread consumer = new Thread (() -> {
17- for (int i = 1 ; i <= 5 ; i ++) {
18- Integer val = queue .dequeue ();
19- System .out .println ("Dequeued: " + val );
20- }
21- });
16+ Thread consumer = new Thread (() -> {
17+ for (int i = 1 ; i <= 5 ; i ++) {
18+ Integer val = queue .dequeue ();
19+ System .out .println ("Dequeued: " + val );
20+ }
21+ });
2222
23- producer .start ();
24- consumer .start ();
25- }
23+ producer .start ();
24+ consumer .start ();
25+ }
2626}
You can’t perform that action at this time.
0 commit comments