@Async 코멘트

Java 응용 프로그램에서, 대부분의 경우는 대화 형 처리 동기화 방식을 통해 달성된다,하지만 상호 작용하는 타사 시스템을 다룰 때 대부분 완료에 여러 개의 스레드를 사용하기 전에, 가능성, 상황에 느린 반응을 일으킬 이러한 작업은, 사실, 봄 3.x를 한 후,이 문제에 @Async의 완벽한 솔루션을 구축하고있다.

이용 @Async 코멘트 조건 :

  • 클래스에서 사용되는 경우, 일반적으로 클래스의 방법에 사용 @Async 노트는,이 클래스의 모든 방법은 비동기 적으로 수행된다;
  • 사용 @Async 클래스 객체 주석 방법은 빈 객체 스프링 컨테이너를 관리해야한다;
  • 클래스에 비동기 메서드 호출은 노트를 구성해야 @EnableAsync

@Async는 간단한 주석을 사용

  • 봄에 @Async을 가능하게하는 방법. 자바 기반의 구성 모드를 사용 :
@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • 전화의 귀환 @Async 기반 :
@Async  //标注使用  
public void asyncMethodWithVoidReturnType() {  
	System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());  
} 
  • 호출에 기반 @Async 반환 값 :
@Async  
public Future<String> asyncMethodWithReturnType() {  
    System.out.println("Execute method asynchronously - "  + Thread.currentThread().getName());  
    try {  
        Thread.sleep(5000);  
        return new AsyncResult<String>("hello world !!!!");  
    } catch (InterruptedException e) {  
        //  
    }  
   
    return null;  
}

위의 예에서 찾을 수 있습니다, 데이터 유형은 인터페이스입니다 미래의 유형에 의해 반환. 특정 결과 유형 AsyncResult,이 노트의 장소입니다.

  • 비동기 메서드 호출의 예로는 결과를 반환합니다 :
public void testAsyncAnnotationForMethodsWithReturnType()  
   throws InterruptedException, ExecutionException {  
    System.out.println("Invoking an asynchronous method. "   + Thread.currentThread().getName());  
    Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();  
   
    while (true) {  ///这里使用了循环判断,等待获取结果信息  
        if (future.isDone()) {  //判断是否执行完毕  
            System.out.println("Result from asynchronous process - " + future.get());  
            break;  
        }  
        System.out.println("Continue doing something else. ");  
        Thread.sleep(1000);  
    }  
}

이러한 비동기 메서드는 결과에 대한 정보를 얻기 위해 끊임없이 미래의 상태를 확인하여 달성을 마치면 현재 비동기 방법을 얻을 수 있습니다.

참고 링크 : https://www.cnblogs.com/wihainan/p/6516858.html

게시 33 개 원래 기사 · 원의 찬양 9 · 전망 8693

추천

출처blog.csdn.net/Serena0814/article/details/97272243