java - 在 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
}
}
请随时评论我实现线程的方法。如果您对如何使它变得更好有建议,这种方法的潜在问题等等。
解决方案
这可能是您需要的近似值:向 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() 时才有效,否则您应该进行一些修改。
这个解决方案有点脏,你可能会通过更多的研究找到更清洁的方法来做你想做的事。
推荐阅读
- scala - scala中的数组断言
- python - 如何测试列表是否包含斜体或粗体文本?
- javascript - 如何在javascript中正确上传文件为base64
- python-3.x - 从 concurrent.futures 获取进度更新
- ios - 如何通过一个导航控制器和另一个导航控制器导航回来?
- sql - 我想从 postgresql 数据库中获取部分数据作为 json 对象
- tortoisesvn - TortoiseSVN 更新后如何单步执行每个文件并解决冲突
- c++ - 使用 C++17 检测类成员是否存在
- javascript - PHP / Javascript 创建新输入取决于用户给出的值
- ruby-on-rails - Ruby on Rails 如何处理没有名称的 JSON 数组