我正在使用一个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
}
}
请随时对我实现线程的方法发表评论。如果你对如何让它变得更好有什么建议,这种方法的潜在问题等等。
发布于 2019-06-05 02:35:17
这可能是您所需要的一个近似值:向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;
}
}
在main方法中:
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()的情况,否则必须进行一些修改。
这个解决方案有点脏,你可以通过更多的研究找到更干净的方法来做你想做的事情。
发布于 2019-06-05 01:52:16
这里有一些选项: 1.实现在线程开始/结束之前/之后触发的回调2.创建一个正在读取静态标志的单独线程,并让另一个线程设置该标志
然而,对我来说,似乎不清楚为什么要使用它?
发布于 2019-06-05 03:31:17
由于您需要按顺序执行这两个方法,因此可以在Spring中使用@DependsOn注释。您可以将它们声明为bean和Spring保证,如果bean A具有B的依赖项,则将首先初始化B。所以bean "firstMethod“的初始化方法"initialize”必须做你需要做的事情
@Component
public class Example{
@Bean(initMethod = "init")
@DependsOn("firstMethod")
public void doSomethingElse() {
//do something. Check flag if needed
}
@Bean(name = "firstMethod", initMethod = "initialize")
public void doSomething() {
//do something.
}
//more methods
}
https://stackoverflow.com/questions/56448920
复制相似问题