-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadSafePrinter.java
More file actions
37 lines (30 loc) · 895 Bytes
/
ThreadSafePrinter.java
File metadata and controls
37 lines (30 loc) · 895 Bytes
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
package creational.singleton;
import java.util.Objects;
public class ThreadSafePrinter implements Printer {
private static ThreadSafePrinter printer;
private ThreadSafePrinter() {
}
public static ThreadSafePrinter getInstance() {
if (Objects.isNull(printer)) {
synchronized (ThreadSafePrinter.class) {
if (Objects.isNull(printer)) {
printer = new ThreadSafePrinter();
}
}
}
return printer;
}
@Override
public synchronized void print(String text) {
try {
for (char c : text.toCharArray()) {
System.out.print(c);
Thread.sleep(75);
}
System.out.println();
Thread.sleep(1000);
} catch (Exception exception) {
exception.printStackTrace();
}
}
}