java - 等待 Spring 应用程序中的线程完成

标签 java spring multithreading threadpoolexecutor

我正在使用 Java Spring 应用程序,并且我已经实现了一个在应用程序启动后启动的线程,如下所示:

@Component
public class AppStartup implements ApplicationListener<ApplicationReadyEvent> {
    @Autowired
    private SomeService service;

    @Override
    public void onApplicationEvent(final ApplicationReadyEvent event) {
        service.executeAsyn();
    }
}

@Service
public class SomeService {
    private TaskExecutor taskExecutor;
    private ApplicationContext applicationContext;

    @Autowired
    private SomeService(TaskExecutor taskExecutor, ApplicationContext applicationContext) {
        this.taskExecutor = taskExecutor;
        this.applicationContext = applicationContext;
    }

    public void executeAsyn() {
        ResellerSyncThread myThread = applicationContext.getBean(MyThread.class);
        taskExecutor.execute(myThread);
    }

    public void methodToExecute() {
        //do something
    }
}

@Component
@Scope("prototype")
public class MyThread implements Runnable {
    @Autowired
    SomeService service;

    @Override
    public void run() {
        service.methodToExecute();
    }
}

本质上,我的目标是在应用程序启动后启动一个线程,其工作是运行一个方法(methodToexecute)并终止。这种方法似乎有效,并且比 ThreadPool 更简单,因为我只想要一个任务。

我的问题是如何等待线程启动然后从主线程完成以进行一些验证。

来自主线程

public class SomeTest {
    @Test
    public void test() {
        //wait for thread to start

        //do something

        //wait for thread to finish

        //do something else

    }
}

也请随意评论我实现该线程的方法。如果您有关于如何改进的建议、这种方法的潜在问题等。

最佳答案

这可能是您所需要的近似值:向 Thread 类添加一个标志,然后在 main 期间检查它。

@Component
@Scope("prototype")
public class MyThread implements Runnable {
    @Autowired
    SomeService service;

    private static boolean done = false;

    public static boolean isDone() {
        return done;
    }

    @Override
    public void run() {
        service.methodToExecute();
        done = true;
    }
}

在主方法中:

public class SomeTest {
    @Test
    public void test() {
        //wait for thread to start

        //do something

        while(!MyThread.isDone())
             Thread.sleep(200); // or some other number you adjust

        //do something else

    }
}

*请注意,这仅在您只运行一次executeAsyn() 时才有效,否则您应该进行一些修改。

这个解决方案有点脏,您可能可以通过更多研究找到更干净的方法来完成您想做的事情。

关于java - 等待 Spring 应用程序中的线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448920/

相关文章:

Spring:如何使用非setter方法注入(inject)属性?

c++ - 两个线程中的同时 abort()

java - 我需要将多个图像下载到目录,以便可以离线访问内容

java - 替换 ZipOutputStream 中的文件

Spring Boot @Autowired 自定义 application.properties

java - 单核和多核上的线程执行

multithreading - Delphi并行编程-多线程速度慢

java - 转换对象的设计

java - 在 Realm 中使用预填充的数据库

java - spring-boot shutdown 兔子 NoClassDefFoundError