1 import java.io.IOException;
2 import java.nio.file.Files;
3 import java.nio.file.Paths;
4 import java.util.ArrayList;
5 import java.util.List;
6 import java.util.Set;
7 import java.util.TreeSet;
8 import java.util.concurrent.ArrayBlockingQueue;
9 import java.util.concurrent.BlockingQueue;
10 import java.util.concurrent.ExecutorService;
11 import java.util.concurrent.Executors;
12
13 public class LongWordFinder
14 {
15 private static String LAST = " LAST ";
16
17 public static Runnable findLongWords(
18 String filename, int minLength, BlockingQueue<String> queue)
19 {
20 return () ->
21 {
22 try
23 {
24 List<String> lines = Files.readAllLines(Paths.get(filename));
25 for (String line : lines)
26 {
27 String[] words = line.split("[\\PL]+");
28 for (String word : words)
29 if (word.length() >= minLength)
30 queue.put(word);
31 }
32 queue.put(LAST);
33 }
34 catch (InterruptedException | IOException ex)
35 {
36 //
37 }
38 };
39 }
40
41 public static void main(String[] args) throws Exception
42 {
43 String[] filenames = {
44 "../longwords/alice30.txt",
45 "../longwords/war-and-peace.txt",
46 "../longwords/crsto10.txt"
47 };
48
49 BlockingQueue<String> queue = new ArrayBlockingQueue<>(50);
50
51 ExecutorService service = Executors.newCachedThreadPool();
52 for (String filename : filenames)
53 {
54 service.submit(findLongWords(filename, 15, queue));
55 }
56
57 Runnable consumer = () ->
58 {
59 try
60 {
61 int completed = 0;
62 Set<String> uniqueLongWords = new TreeSet<>();
63 while (completed < filenames.length)
64 {
65 String word = queue.take();
66 if (word == LAST) completed++;
67 else uniqueLongWords.add(word);
68 }
69 for (String word : uniqueLongWords)
70 {
71 System.out.println(word);
72 }
73 }
74 catch (InterruptedException ex)
75 {
76 //
77 }
78 };
79 service.submit(consumer);
80 service.shutdown();
81 }
82 }