有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从主线程启动并行线程并等待结果

我需要启动执行一些任务的并行线程,然后唤醒主线程。我的代码是:

            class TokenThread extends Thread implements Runnable {

                public String local_token = null;

                private Object monitor = null;

              public TokenThread(Object monitor) {

                    this.monitor = monitor;

                }

                @Override
                public void run() {

                    try {

                        local_token = GoogleAuthUtil.getToken(activity, mEmail, SCOPE);

                    } catch (IOException e) {

                    } catch (GoogleAuthException e) {

                    }

// think that this thread must wait for main thread end

// his synchronized (monitor) block but it doesn't work 
                    synchronized (monitor) { 

                        monitor.notify();

                    }

                }

            } // END: class TokenThread


                // Creation of the monitor
                Object monitor = new Object();

                // New thread creation
                TokenThread getTokenThread = new TokenThread(monitor);

                try {

                    synchronized (monitor) { // Try to block object

                        getTokenThread.run();

                        monitor.wait(); // may wait(10000) for emergency

                    }


                } catch (InterruptedException e) {


                }

// Reciving a result from paralel thread object
                token = getTokenThread.local_token;

问题是getTokenThread end在主线程对监视器对象进行等待调用之前运行函数。结果-主线程在结束读取后进入睡眠状态,没有人能唤醒它

这段代码在Asynk任务中工作,不试图阻止用户界面


共 (1) 个答案

  1. # 1 楼答案

    如果您知道自己在做什么(不阻塞gui线程等),那么可以使用Thread#join().

    例如:

    final Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 5; i++) {
                        System.out.println(i);
                        try {
                            Thread.sleep(1000);
                        } catch (final InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            t.start();
            t.join();
            System.out.println("Thread is done!");