Код: Выделить всё
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class TestThreads {
private static final Scanner scanner = new Scanner(System.in);
private static ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
private static LinkedBlockingQueue names = new LinkedBlockingQueue();
public static void main(String[] args) {
executor.submit(() -> {
try {
while (true) {
String name = getName();
names.add(name);
}
} catch (Exception e) {
e.printStackTrace();
}
});
executor.submit(() -> {
try {
while (true) {
if (!names.isEmpty()) {
String name = names.poll();
System.out.println("\n**** The name is " + name + " ****\n");
}
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
private static String getName() {
System.out.print("Enter a name: ");
return scanner.nextLine();
}
}
Код: Выделить всё
Enter a name:
Process finished with exit code 0
Подробнее здесь: https://stackoverflow.com/questions/777 ... s-before-g