@Async实际上并没有在另一个线程中调用方法

时间:2017-11-16 11:01:25

标签: java spring asynchronous concurrency

我有以下代码:

主要

@SpringBootApplication
@EnableAsync
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

在某些地方我有这样的代码:

public enum EmailMessage {
    ....
    void sendSilent(String from, String[] recipients, Map<String, ?> properties) {
            long start= System.currentTimeMillis();
            try {

                emailService.sendEmail(from, this.subject, recipients, properties, this.templateFileName);
            } catch (Exception e) {
                LOGGER.warn("Could not send email", e);
            }
            finally {
                System.out.println("Result:" + (System.currentTimeMillis()- start)/1000 + " Thread:" + Thread.currentThread().getId());
                System.out.println();
            }
        }
}

我在这里设置 emailService

    @Service
    public static class EmailService {
        @PostConstruct
        public void initialize() {
            //to provide reference to EmailService to enum because enum could not be component
            EmailMessage.emailService = this;
        }
        ....
    }

sendEmail:

    @Async
    public void sendEmail(String from, String subject, String[] to, Map<String, ?> props, String templateFileName) throws Exception {
        .... //here some which executes slowly
        System.out.println( " sendEmail Thread:" + Thread.currentThread().getId());
   }

我提供的代码产生以下输出:

 sendEmail Thread:1
Result:9 Thread:1

正如您可以看到两种方法的线程相同。代码执行9秒。

我错了什么?

0 个答案:

没有答案