why this code
public static void main(String [] argv){
Logger l = LoggerFactory.getLogger( "MAIN" );
Thread thread = new Thread(()->{
Logger ll = LoggerFactory.getLogger( "WRKR" );
ll.debug("start t1");
try {
Thread.sleep( 10000 );
} catch (InterruptedException e) {
throw new RuntimeException( e );
}
ll.debug("end t1");
}) ;
l.info("main");
thread.start();
try {
Thread.sleep( 8000 );
} catch (InterruptedException e) {
throw new RuntimeException( e );
}
try {
l.info("trying to join");
thread.join(100);
l.info("joined");
} catch (InterruptedException e) {
throw new RuntimeException( e );
}
l.info("end main");
}
produces this output:
10:57:38.871 [main] INFO MAIN - main
10:57:38.879 [Thread-0] DEBUG WRKR - start t1
10:57:46.884 [main] INFO MAIN - trying to join
10:57:46.993 [main] INFO MAIN - joined
10:57:46.993 [main] INFO MAIN - end main
10:57:48.880 [Thread-0] DEBUG WRKR - end t1
What's the point of join(100) not informing that the "worker" thread is still running? I'd have expected a runtime exception.
The javadoc for join(long millis) method states "Waits at most millis milliseconds for this thread to terminate". It does not report the current state of the other thread so after your call thread.join(100);
you don't have any information on the state of thread
.
Since JDK19 you can use join with Duration which returns boolean which tells you whether the thread has terminated. If you view the source of join(Duration)
it is equivalent to join(millis);
with test isTerminated();
so you can call thread.isTerminated()
if not currently using JDK19+.