以下 java prgram 将输出什么 - 是否总是如下所述,或者存在任何可能不同的极端情况 -
预期输出 -
task1 关键部分已完成
task2 关键部分已完成
Java 程序 -
import java.util.concurrent.CountDownLatch;
public class CountDownLatchTest2 {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(1);
RunnableTask1 task1 = new RunnableTask1(countDownLatch);
RunnableTask2 task2 = new RunnableTask2(countDownLatch);
Thread t2 = new Thread(task2);
Thread t1 = new Thread(task1);
t1.start();
t2.start();
}
static class RunnableTask1 implements Runnable
{
private CountDownLatch countDownLatch;
public RunnableTask1(CountDownLatch countDownLatch)
{
this.countDownLatch = countDownLatch;
}
@Override
public void run()
{
System.out.println("task1 critical section completed");
countDownLatch.countDown();
}
}
static class RunnableTask2 implements Runnable
{
private CountDownLatch countDownLatch;
public RunnableTask2(CountDownLatch countDownLatch)
{
this.countDownLatch = countDownLatch;
}
@Override
public void run()
{
try
{
countDownLatch.await();
System.out.println("task2 critical section completed");
}
catch (InterruptedException e)
{
System.out.println("task 2 has been interupted");
}
}
}
}