gpt4 book ai didi

java - Spring运行独立线程

转载 作者:行者123 更新时间:2023-12-01 18:18:06 24 4
gpt4 key购买 nike

我正在运行带有 spring security 3.2 的 v4 Spring mvc 应用程序我正在尝试从 Controller 运行独立线程

@Controller
public class C1{
@AutoWired
C2 c2;

@RequestMappting("/")
public String home(){
c2.run();
System.out.println("something");
return "home";
}
}
}

@Component
@Scope
public class C2 extends Thread{
@Override
public void run(){
while(true){
System.out.println("random stuff");
}
}
}

当我运行此代码时,它陷入c2.run(); 下一行不执行;我在这里想要实现的是连续打印随机内容并渲染 home.jsp 页面
我做错了什么,如何解决这个问题???

最佳答案

使用Spring框架时不需要直接使用Threads。它有一个很棒的Task Execution and Scheduling应该使用的抽象。这样你想要的就可以实现。

@Controller
public class C1{
@AutoWired
C2 c2;

@RequestMappting("/")
public String home(){
c2.run();
System.out.println("something");
return "home";
}
}

@Component
@Scope
public class C2{

@Async
public void run(){
while(true){
System.out.println("random stuff");
}
}
}

@Configuration
@EnableAsync
public class AppConfig implements AsyncConfigurer {

@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("MyExecutor-");
executor.initialize();
return executor;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return MyAsyncUncaughtExceptionHandler();
}

}

关于java - Spring运行独立线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28406630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com