【问题标题】:How I can Perform certain task in main thread based on the response from other thread?如何根据其他线程的响应在主线程中执行某些任务?
【发布时间】:2021-11-02 23:46:56
【问题描述】:

主线程(RunnableTest)不应等待其他线程(RunnableExample)执行循环以打印从0到4的数字。主线程和其他线程将并行执行。再次接收到从其他线程返回的结果后,主线程将处于动作模式。我怎样才能做到这一点?

我有一个主线程,如下所示:

public class RunnableTest {
    public static void main(String[] args) {
        //some code
        new RunnableExample();
        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }
        // Upon receiving result from RunnableExample thread again main thread will be in action and perform some task
    }
}

另一个执行特定任务的线程:

public class RunnableExample implements Runnable {
    boolean isAvailable = false;
    Thread thread;

    public RunnableExample() {
        thread = new Thread(this);
        thread.start();
    }

    public void run() {
        isAvailable = checkForAvailability();
    }

    private boolean checkForAvailability() {
        // some task
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
        return true;
    }
}

【问题讨论】:

  • 问题是什么?
  • RunnableExample 的构造函数中创建的本地线程不使用RunnableExample 的方法run,因此也不会调用checkForAvailability。该线程应声明为:public RunnableExample() { new Thread(this).start();}
  • @AlexRudenko run 方法将在 thread.start() 将在 RunnableExample() 构造函数中执行时执行。我正在 RunnableTest 类中创建 RunnableExample 类的对象。
  • @Srikant,不,它没有。没有为构造函数中启动的线程实例提供RunnableExample(实现Runnable)的实例。
  • @AlexRudenko 对不起我的错误!更新了

标签: java multithreading java.util.concurrent


【解决方案1】:

如何根据其他线程的响应在主线程中执行某些任务?

如果我理解您的问题,答案是使用thread.join();。当你从主线程 fork RunnableExample 线程时,它们都并行运行,但主线程需要等待另一个线程才能继续。

// this just creates the object, it doesn't start the thread
RunnableExample example = new RunnableExample();
// create the thread object with the example as the Runnable
Thread thread = new Thread(example);
// start the thread running, it will call RunnableExample.run()
thread.start();
// now main does what it needs to do in parallel with the background thread
for (int i = 0; i < 5; i++) {
   ...
}
// later it should join on background thread, it will wait for it to finish
thread.join();
// it then can read any fields from the example object
System.out.println("isAvailable = " + example.isAvailable);

重要的是要了解,如果没有join() 调用,主线程将无法访问example.isAvailable 字段,因为内存尚未同步。一旦join() 返回,则保证主线程正确更新example 中的内存。

【讨论】:

    【解决方案2】:

    使用拉动,将是最简单的。

    1. 使用 Singleton,在两个线程之间拥有相同的共享对象。

    2. Use a Lock l 女巫用于输入 3 种方法中的任何一种。

      一个。 hasMessage()(查看列表)

      b. getMessage() (退出列表)

      c。 putMessage(Object elem) (将 elem 添加到列表中)

    只要主线程准备就绪(例如每 100 次迭代),它就会检查 hasMessage() 是否为真。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-05
      • 2020-04-06
      • 1970-01-01
      • 2017-02-28
      • 2010-11-15
      • 2022-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多