Created
June 27, 2022 16:03
-
-
Save sshark/fa9fbbdc52bfc6a7f4eaeec505b556aa to your computer and use it in GitHub Desktop.
Who is first?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.teckhooi.foo; | |
import java.util.Objects; | |
public class WhosFirst { | |
static private Long t1 = null; | |
static private Long t2 = null; | |
static private Object lock = new Object(); | |
static private long startMillis = 0; | |
public static void main(String[] args) throws Exception { | |
startMillis = System.currentTimeMillis(); | |
Thread first = new Thread(() -> { | |
System.out.printf("Runner1 starts.. %s\n", Thread.currentThread().getName()); | |
try { | |
Thread.sleep(1100); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
t1 = System.currentTimeMillis() - startMillis; | |
System.out.printf("Runner1 on %s wins after %dms\n", Thread.currentThread().getName(), t1); | |
synchronized (lock) { | |
lock.notify(); | |
} | |
}); | |
Thread second = new Thread(() -> { | |
System.out.printf("Runner2 starts.. %s\n", Thread.currentThread().getName()); | |
try { | |
Thread.sleep(1000); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
t2 = System.currentTimeMillis() - startMillis; | |
System.out.printf("Runner2 on %s wins after %dms\n", Thread.currentThread().getName(), t2); | |
synchronized (lock) { | |
lock.notify(); | |
} | |
}); | |
first.setDaemon(true); | |
second.setDaemon(true); | |
first.start(); | |
second.start(); | |
synchronized (lock) { | |
lock.wait(); | |
} | |
System.out.printf("Done... t1=%d, t2=%d\n", t1, t2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment