如何在多线程环境下从多个String类型List中搜索指定字符串?
Got it, let's walk through a practical, clean implementation to solve this problem. We'll assign each list to its own thread to search for the string "good", using Java's core concurrency tools since you're working with List<String> objects.
Step 1: Create a Reusable Search Task
First, we'll define a Runnable class that wraps the search logic. This task will take a list, the target string, and a name for the list (to make results clear), then handle the search and output the outcome.
import java.util.List; class SearchTask implements Runnable { private final List<String> targetList; private final String searchString; private final String listIdentifier; public SearchTask(List<String> targetList, String searchString, String listIdentifier) { this.targetList = targetList; this.searchString = searchString; this.listIdentifier = listIdentifier; } @Override public void run() { boolean isFound = targetList.contains(searchString); String resultMessage = isFound ? String.format("✅ Found '%s' in %s", searchString, listIdentifier) : String.format("❌ Did NOT find '%s' in %s", searchString, listIdentifier); System.out.println(resultMessage); } }
Step 2: Set Up Lists and Launch Threads
Next, we'll initialize your lists as specified, create a thread for each, and start them. We'll use Thread.join() to wait for all threads to finish (optional, but useful if you need to run code after all searches complete).
import java.util.Arrays; import java.util.List; public class MultiThreadListSearch { public static void main(String[] args) throws InterruptedException { // Initialize your lists with the given content List<String> str1 = Arrays.asList("i", "need", "help."); List<String> str2 = Arrays.asList("This", "is", "a", "good", "program."); List<String> str3 = Arrays.asList("i", "need", "solution."); List<String> str4 = Arrays.asList("i", "need", "solution", "using", "multi-thread", "concept."); // Create threads for each list Thread threadStr1 = new Thread(new SearchTask(str1, "good", "str1")); Thread threadStr2 = new Thread(new SearchTask(str2, "good", "str2")); Thread threadStr3 = new Thread(new SearchTask(str3, "good", "str3")); Thread threadStr4 = new Thread(new SearchTask(str4, "good", "str4")); // Start all threads threadStr1.start(); threadStr2.start(); threadStr3.start(); threadStr4.start(); // Wait for all threads to complete execution (optional) threadStr1.join(); threadStr2.join(); threadStr3.join(); threadStr4.join(); System.out.println("\nAll search threads have finished running."); } }
Key Details to Note:
- Thread Isolation: Each thread works independently on its own list, so there's no shared mutable state to synchronize (no race conditions here since we're only reading from the lists).
- Result Collection: If you need to collect results instead of printing them directly, you could use a thread-safe collection like
ConcurrentHashMap<String, Boolean>to store whether each list contained the target string. - Alternative Thread Management: For larger numbers of tasks, using
ExecutorService(e.g.,Executors.newFixedThreadPool(4)) is cleaner than creating threads manually—it handles thread pooling and lifecycle management for you.
Example Output:
❌ Did NOT find 'good' in str1 ✅ Found 'good' in str2 ❌ Did NOT find 'good' in str3 ❌ Did NOT find 'good' in str4 All search threads have finished running.
内容的提问来源于stack exchange,提问作者Prasoon Kumar

