Web应用程序中的Spring线程

我正在为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。

我的做法有什么不对?

您可以使用@Scheduled(fixedDelay = 5000)定期执行方法。 请记住为包含main方法的类设置@EnableScheduling

@Scheduled注释有两个选项 – fixedDelayfixedRate

fixedDelay将在上次执行完成后延迟X毫秒继续执行您的方法。

fixedRate将在固定日期继续执行您的方法。 因此,无论上次执行是否完成,每X毫秒都会执行此方法。

如果要一次处理一堆对象,也可以使用@Async 。 再一次,您需要使用main方法将@EnableAsync添加到您的类中。

 //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 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++; } } 

奖励您可以通过扩展AsyncConfigurerSupport并覆盖getAsyncExecutor来消除池大小的XML配置。 有关此方法的更多信息,请参见以下链接

我建议你看看:

https://spring.io/guides/gs/scheduling-tasks/

https://spring.io/guides/gs/async-method/

您可以使用@Async,以防您想以编程方式调用单个线程(例如,您希望发送50个邮件,然后发送它们创建50个不同的线程,每个线程发送一条消息,然后等待所有线程结束),或@计划让方法/线程以固定速率运行(或者从前一个执行结束一段时间后)。

您可以关注https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support以获取更多详细信息。

 @Service public class MyAsyncStuff { @Async public Future callMe(String param) { // do your work here... return new AsyncResult("Sent: "+param); } } @Service public class MyWorker { @Inject MyAsyncStuff stuff; public void invoker() { List> futures = new Arraylist<>(); for (int i=0; i<10; i++) { futures.add(stuff.callMe("Invoked "+i)); } for (Future fut : futures) { try { System.out.println(futures.get(); } catch (Exception e) { // Spock? Do something! } } } }