我正在为MMO浏览器游戏编写服务器,我需要创建几个线程。
他们将一直运行,并有一些睡眠时间。
使用这样的弹簧线是个好主意吗?
@Component
@Scope("prototype")
public class PrintTask2 implements Runnable{
String name;
public void setName(String name){
this.name = name;
}
@Override
public void run() {
System.out.println(name + " is running");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " is running");
}
}
任务执行器作为 bean 实现?
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5" />
<property name="maxPoolSize" value="10" />
<property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>
此外,线程是在也定义为 bean 的单例中启动的。
我的方法可能有什么问题?
您可以使用@Scheduled(fixedDelay = 5000)
定期执行方法。记得设置一下@EnableScheduling
对于包含您的 main 方法的类。
有两种选择@Scheduled
注释-fixedDelay
and fixedRate
.
fixedDelay
将在最后一次执行完成后延迟 X 毫秒继续执行您的方法。
fixedRate
将在固定日期连续执行您的方法。因此,无论最后一次执行是否完成,每 X 毫秒都会执行此方法。
您还可以使用@Async
如果你想一次处理一堆对象。再次,您需要添加@EnableAsync
使用您的 main 方法到您的班级。
Example
//Remember to set @EnableScheduling
//in the class containing your main method
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}
@Component
public class ScheduledTasks {
List<YourObject> myObjects;
//This method will run every 5 second.
@Scheduled(fixedDelay = 5000)
public void yourMethodName() {
//This will process all of your objects all at once using treads
for(YourObject yo : myObjects){
yo.process();
}
}
}
public class YourObject {
Integer someTest = 0;
@Async
public void process() {
someTest++;
}
}
Bonus您可以通过扩展来摆脱池大小的 XML 配置AsyncConfigurerSupport
并覆盖getAsyncExecutor
。有关此方法的更多信息可以在以下链接中找到
我建议你看一下:
https://spring.io/guides/gs/scheduling-tasks/ https://spring.io/guides/gs/scheduling-tasks/
https://spring.io/guides/gs/async-method/ https://spring.io/guides/gs/async-method/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)