从main开始并行线程并等待结果

时间:2016-03-22 05:19:43

标签: java android multithreading asynchronous

我需要启动执行某项工作的并行线程,然后唤醒主线程。我的代码是:

            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在主线程对监视器对象进行等待调用之前结束它的运行功能。结果 - 主线程在getTokenThread结束后进入休眠状态,没有人可以唤醒它。

PS。此代码在Asynk任务中工作,而不是试图阻止UI

1 个答案:

答案 0 :(得分: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!");