spring_@Async_写给自己看的

@Configuration  //把bean加入spring
@EnableAsync  //启用异步注解
@Async             //在具体的异步方法上标注后,该方法调用即为异步 (注意在调用该方法时一定要经过代理)

异步方法可以有返回值  通过Future模式返回  通过AsynchResout<Xxxx>(xxx);来构建

异步类
 

package com.qbsea.modules.zexample1.service;
import java.util.concurrent.Future;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AsyncTestService {
	@Async
	public void asyncMethod() {
		try {
			System.out.println("asyncMethod start");
			Thread.sleep(20000);
			System.out.println("asyncMethod end");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Async
	public Future<String>  asyncMethodReturn() {
		try {
			System.out.println("asyncMethod start");
			Thread.sleep(20000);
			System.out.println("asyncMethod end");
			return new AsyncResult<String>("hello world !!!!"); 
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}

调用异步类的入口

public String asynctestMethod() {
		asyncTestService.asyncMethod();
		return "method complete";
	}
	
	public void asynctestMethodReturn() throws InterruptedException, ExecutionException {
		System.out.println("asynctestMethodReturn start");
		Future<String> future  = asyncTestService.asyncMethodReturn();
		System.out.println("asynctestMethodReturn start111");
		System.out.println(future.get());
	}


 

猜你喜欢

转载自blog.csdn.net/maqingbin8888/article/details/81775162