【问题标题】:Starting parallel thread from main and waiting for result从 main 启动并行线程并等待结果
【发布时间】:2016-03-22 05:19:43
【问题描述】:

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

            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 结束后进入睡眠状态,没有人可以唤醒它。

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

【问题讨论】:

  • 要启动线程,调用getTokenThread.start(),而不是run()。并考虑完全不阻塞 UI 线程,因为这是非常不鼓励的做法。
  • 您是否为此尝试过异步任务。 developer.android.com/intl/in/reference/android/os/… ?
  • 这项工作在 Asynk 任务中,需要一个多线程来进行 HTTP 连接。停止 HTTP 连接的问题。通过使用 disconnect() 方法,我无法立即终止 HTTP 连接。仍然尝试在 5-20 秒之前连接将引发 IO 异常。想法是创建新线程并销毁它以杀死线程内的 HTTP 连接。

标签: java android multithreading asynchronous


【解决方案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!");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多