叙述完整的例子使用CountDownLatch
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Race {
public static void main(String[] args) {
boolean flag=true; //set false to see other behavior
if (flag) {
startRace(5L, 2L);
} else {
startRace(2L, 5L);
}
}
private static void startRace(final long s1, final long s2) {
new Thread() {
@Override
public void run() {
Test.t1(s1);
}
}.start();
new Thread() {
@Override
public void run() {
Test.t2(s2);
}
}.start();
}
}
class Test {
static volatile int flag = 0;
static CountDownLatch L = new CountDownLatch(1);
public static void t1(long n) {
await(n);
logic1();
L.countDown(); // comment to wait till end
}
public static void t2(long n) {
await(n);
logic2();
L.countDown();
}
private static void logic1() {
if (flag == 0) {
System.out.println(Thread.currentThread()
+ ": Flag Couldnt be set in time");
} else {
System.out.println(Thread.currentThread() + ": Flag set in time");
}
}
private static void logic2() {
flag = 1;
System.out.println(Thread.currentThread() + ": Flag Set");
}
private static void await(long n) {
waitMsg(n);
try {
if (L.await(n, TimeUnit.SECONDS)) {
waitOverBefore(n);
} else {
waitOver(n);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void waitOverBefore(long n) {
System.out.println(Thread.currentThread() + ": Waiting Over before "
+ n + " seconds");
}
private static void waitOver(long n) {
System.out.println(Thread.currentThread() + ":" + n
+ " seconds Waiting Over");
}
private static void waitMsg(long n) {
System.out.println(Thread.currentThread() + ":Waiting for " + n
+ " seconds");
}
}
输出 1
Thread[Thread-0,5,main]:Waiting for 5 seconds
Thread[Thread-1,5,main]:Waiting for 2 seconds
Thread[Thread-1,5,main]:2 seconds Waiting Over
Thread[Thread-1,5,main]: Flag Set
Thread[Thread-0,5,main]: Waiting Over before 5 seconds
Thread[Thread-0,5,main]: Flag set in time
输出 2
Thread[Thread-1,5,main]:Waiting for 5 seconds
Thread[Thread-0,5,main]:Waiting for 2 seconds
Thread[Thread-0,5,main]:2 seconds Waiting Over
Thread[Thread-0,5,main]: Flag Couldnt be set in time
Thread[Thread-1,5,main]: Waiting Over before 5 seconds
Thread[Thread-1,5,main]: Flag Set