如何实现线程运行直至两个Integer值相等后停止并触发函数?
Hey there! Let's walk through how to set up a background check for two Integer values—stopping the thread when they match and triggering your custom function. I'll cover two practical approaches, plus key pitfalls to avoid.
Approach 1: Basic Thread with Loop Check
This is a straightforward method where a dedicated thread runs a loop, checks for equality at intervals, and exits when the condition is met. We'll use a volatile flag to safely control thread termination (never use Thread.stop()—it's unsafe and deprecated!).
public class IntegerChecker { // Volatile ensures visibility of value changes across threads private volatile boolean running = true; private Integer targetValue; private Integer monitoredValue; private Runnable onMatchAction; public IntegerChecker(Integer monitoredValue, Integer targetValue, Runnable onMatchAction) { this.monitoredValue = monitoredValue; this.targetValue = targetValue; this.onMatchAction = onMatchAction; } public void startCheck() { Thread checkThread = new Thread(() -> { while (running) { // Critical: Use .equals() for Integer equality! // == only works for values between -128 and 127 due to Integer caching if (targetValue.equals(monitoredValue)) { // Stop the thread loop running = false; // Trigger your custom function onMatchAction.run(); break; } // Add a small delay to avoid spiking CPU usage try { Thread.sleep(100); // Adjust delay based on your needs } catch (InterruptedException e) { // Handle thread interruption gracefully Thread.currentThread().interrupt(); running = false; } } }); checkThread.start(); } // Optional: Manually stop the check if needed public void stopCheck() { running = false; } } // Usage example public class Main { public static void main(String[] args) { Integer monitored = 42; Integer target = 42; Runnable myCustomFunction = () -> System.out.println("Values matched! Running custom logic..."); IntegerChecker checker = new IntegerChecker(monitored, target, myCustomFunction); checker.startCheck(); } }
Approach 2: ScheduledExecutorService for Periodic Checks
If you don't want a continuous loop, using ScheduledExecutorService lets you schedule periodic checks—this is more efficient as it doesn't tie up a thread in a tight loop.
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledIntegerChecker { private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); private Integer targetValue; private Integer monitoredValue; private Runnable onMatchAction; public ScheduledIntegerChecker(Integer monitoredValue, Integer targetValue, Runnable onMatchAction) { this.monitoredValue = monitoredValue; this.targetValue = targetValue; this.onMatchAction = onMatchAction; } public void startCheck() { // Schedule check to run immediately, then repeat every 100ms scheduler.scheduleAtFixedRate(() -> { if (targetValue.equals(monitoredValue)) { // Shutdown the scheduler to stop all tasks scheduler.shutdown(); onMatchAction.run(); } }, 0, 100, TimeUnit.MILLISECONDS); } // Optional: Manual shutdown public void stopCheck() { scheduler.shutdownNow(); } } // Usage example public class Main { public static void main(String[] args) { Integer monitored = 100; Integer target = 100; Runnable myCustomFunction = () -> { System.out.println("Values matched! Executing custom function..."); // Add your specific logic here }; ScheduledIntegerChecker checker = new ScheduledIntegerChecker(monitored, target, myCustomFunction); checker.startCheck(); } }
Critical Notes to Remember
- Integer Equality: Always use
Integer.equals()instead of==! The==operator checks object references, not actual values. For integers outside-128to127, Java doesn't cache Integer objects, so==will fail even if values are identical. - Thread Safety: Use
volatileflags or proper synchronization if the monitored/target values are modified by other threads. Without this, the background thread might not see the latest value changes. - Resource Cleanup: Always shut down executors or set termination flags when done to avoid leaking threads.
- Interruption Handling: If your thread might be interrupted (e.g., during application shutdown), handle
InterruptedExceptionproperly and restore the interrupted status if needed.
内容的提问来源于stack exchange,提问作者Carl Fredrik Ahl

