join with Milliseconds and Nanoseconds
You'll learn how to wait for a thread to finish with nanosecond-level precision using join(long millis, int nanos).
The Precision Timing Method
You've already seen join() wait indefinitely and join(long millis) wait with millisecond precision. Java offers an even finer control: join(long millis, int nanos) combines milliseconds with nanoseconds for extremely precise timeout specifications.
How It Works
The signature is:
public final void join(long millis, int nanos) throws InterruptedException
millis: Base timeout in milliseconds (0 to Long.MAX_VALUE)nanos: Additional nanoseconds (0 to 999,999)
The total wait time is millis + nanos/1,000,000 milliseconds.
Important constraint: nanos must be in the range 0–999,999, or you'll get an IllegalArgumentException.
Example Usage
Thread worker = new Thread(() -> {
try {
Thread.sleep(100);
System.out.println("Work done");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
worker.start();
// Wait 50 milliseconds + 500,000 nanoseconds (50.5 ms total)
worker.join(50, 500_000);
if (worker.isAlive()) {
System.out.println("Worker still running after precise timeout");
}
Real-World Considerations
While this method offers nanosecond precision in your intent, actual OS thread scheduling typically operates at millisecond granularity. The nanosecond parameter gives you precise specification, but don't expect true nanosecond accuracy in execution timing.
Key Takeaway: Use join(long millis, int nanos) when you need to express very precise timeout requirements, combining milliseconds and nanoseconds for sub-millisecond control—though actual scheduling precision depends on the operating system.