Skip to content

Commit 51fff7f

Browse files
feat: add simple thread-safe queue using synchronized
1 parent 9cd54ee commit 51fff7f

2 files changed

Lines changed: 73 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.thealgorithms.datastructures.queues;
2+
3+
public class ThreadSafeQueue<T> {
4+
5+
private static class Node<T> {
6+
T data;
7+
Node<T> next;
8+
9+
Node(T data) {
10+
this.data = data;
11+
}
12+
}
13+
14+
private Node<T> head;
15+
private Node<T> tail;
16+
17+
public synchronized void enqueue(T data) {
18+
Node<T> newNode = new Node<>(data);
19+
20+
if (tail == null) {
21+
head = tail = newNode;
22+
return;
23+
}
24+
25+
tail.next = newNode;
26+
tail = newNode;
27+
}
28+
29+
public synchronized T dequeue() {
30+
if (head == null) {
31+
return null;
32+
}
33+
34+
T data = head.data;
35+
head = head.next;
36+
37+
if (head == null) {
38+
tail = null;
39+
}
40+
41+
return data;
42+
}
43+
44+
public synchronized boolean isEmpty() {
45+
return head == null;
46+
}
47+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.thealgorithms.datastructures.queues;
2+
3+
public class ThreadSafeQueueTest {
4+
5+
public static void main(String[] args) {
6+
7+
ThreadSafeQueue<Integer> queue = new ThreadSafeQueue<>();
8+
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+
});
15+
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+
});
22+
23+
producer.start();
24+
consumer.start();
25+
}
26+
}

0 commit comments

Comments
 (0)