使用CountDownLatch

时间:2015-11-22 03:52:39

标签: java countdownlatch

以下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");
        }           
    }
}
}

1 个答案:

答案 0 :(得分:1)

输出始终是预期的输出。

countDownLatch.countDown();发生在countDownLatch.await();之前var App = React.createClass({ clearText() { this._textInput.setNativeProps({text: ''}); }, render() { return ( <View style={styles.container}> <TextInput ref={component => this._textInput = component} style={styles.textInput} /> <TouchableOpacity onPress={this.clearText}> <Text>Clear text</Text> </TouchableOpacity> </View> ); } }); 取消阻止。