0

以下是我使用 CountDownLatch 和 ExecutorService 的课程。我所有的 startTest 方法都来自我的活动。当我运行此代码时,CountdownLatch 不会等待。

public class Test implements Tester.StartListener, Tester.StopListener, Runnable{
    private CountDownLatch latch;
    ExecutorService executorService;
    Context context;
    ListElement listElement;
    int countDown;


    final String user = "palapi_android@tourmalinelabs.com";

    public Test(Context context) {
        this.context = context;
        this.listElement = listElement;
    }

    public void startTest(int nTimes) throws InterruptedException {
        this.countDown = nTimes;
        executorService = Executors.newSingleThreadExecutor();
        latch = new CountDownLatch(countDown);
        executorService.execute(this);
        latch.await();
    }

    @Override
    public void run() {
        setText("Running");
        Tester.Start(context, user, this);

    }

    @Override
    public void OnStarted() {
        Tester.Stop(context, this);
    }

    @Override
    public void OnFail( int reason ) {
        Log.d("Failure", "failed because " + reason);

    }

    @Override
    public void OnStopped() {
        setText(String.valueOf(countDown));
        countDown --;
        latch.countDown();
        if( countDown >= 0) {
            runAfterDelayInRange(new Runnable() {
                @Override
                public void run() {
                    Tester.Start(context, user, Test.this);
                }
            });
        } else {
            setText("Done");
        }
    }

    protected void setText(final String text) {
        getHandler().post(new Runnable() {
            @Override
            public void run() {
                if (listElement != null) {
                    listElement.setTestResult(text);
                }
                LauncherActivity activity = (LauncherActivity) context;
                activity.notifyDataSetChanged();
            }
        });
    }


    protected void runAfterDelayInRange(Runnable action) {
        getHandler().post(action);
    }


    private Handler getHandler(){
        return new Handler(context.getMainLooper());
    }

}

有人可以告诉我我做错了什么吗?先感谢您

4

0 回答 0