1

我正在使用一个线程从我的数据库中获取一个 id。一旦线程完成运行,我需要在另一个线程中使用该 id 来获取项目列表。一旦该线程完成,我将使用项目列表来填充微调器。我遇到的问题是它在线程返回项目列表之前填充微调器。我怎样才能使它在线程完成运行之前不会填充微调器?

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        String bookName = existingBooks.get((int) spinner.getSelectedItemId());

                        Book myBook = AppDatabase.getInstance(getContext()).bookDAO().getBookByTitle(bookName);

                        long book_Id = myBook.getBook_id();

                        existingCountDates = AppDatabase.getInstance(getContext()).countDAO().getCountDatesInBook(book_Id);

                        List<Count> Counts = AppDatabase.getInstance(getContext()).countDAO().getAllCounts();

                        Log.e("Dates", existingCountDates.toString());
                        Log.e("All Counts", Counts.toString());

                    }
                }).start();

                //TODO: FIX THIS ISSUE
                Log.e("Problem:", "This gets called before the thread finishes. Not sure how to fix it");
                str_adapter.clear();
                for (int i = 0; i < existingCountDates.size(); i++) {
                    str_adapter.add(existingCountDates.get(i));
                }
                str_adapter.notifyDataSetChanged();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //TODO: DISABLE OTHER DROPDOWN MENUS?
            }
        });

在此处输入图像描述

4

3 回答 3

0

您可以使用另一个线程并等待上一个线程,直到使用 thread.join() 完成。但是更好的版本是使用ExecutorServices,例如ThreadPoolExecutor

代码实验室

于 2021-08-20T22:10:31.367 回答
0

我不确定这是否会对您有所帮助。但是您可以使用 bool 变量来检查线程是否已完成其工作。

bool flag = false;
new Thread(new Runnable() {
    @Override
    public void run() {
        //statements
        flag = true;
    }
}).start();
while(flag != true);
//statements to be executed after completion of thread.

注意:确保执行永远不会进入无限循环。

于 2021-08-21T14:38:26.943 回答
0

我怎样才能使它在线程完成运行之前不会填充微调器?

有几种方法可以做到这一点。最简单的可能是获得ExecutorService通常推荐的,而不是Thread“手动”创建。这也允许您从作业中返回一个值,在这种情况下您提交 aCallable<?>而不是 a Runnable

ExecutorService threadPool = Executors.newFixedThreadPool(1);
...
Future<Void> future = threadPool.submit(new Runnable() {
    public void run() {
       ...
    }
});
// wait for this job to finish
future.get();
...
// when you are done with the pool you need to shut it down
threadPool.shutdown();

您也可以启动一个线程,然后join()使用它。等待线程完成。

Thread thread = new Thread(new Runnable() { ... });
thread.start();
// now we can do stuff while the thread runs in the background
...
// wait for the thread to finish before returning
thread.join();
...

get()方法或join()方法还意味着existingCountDates在作业内部修改的或任何其他内容将在调用者的内存中适当地更新。

于 2021-08-24T19:09:25.937 回答