首页 > 解决方案 > 在 Spring 应用程序中等待线程完成

问题描述

我正在使用 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

    }
}

请随时评论我实现线程的方法。如果您对如何使它变得更好有建议,这种方法的潜在问题等等。

标签: javaspringmultithreadingthreadpoolexecutor

解决方案


这可能是您需要的近似值:向 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() 时才有效,否则您应该进行一些修改。

这个解决方案有点脏,你可能会通过更多的研究找到更清洁的方法来做你想做的事。


推荐阅读