본문 바로가기
Java

자바 Async1

by NaHyungMin 2020. 11. 8.

자바에 Async는 C#과 사용법에 차이가 좀 있다.

자바는 어노테이션을 사용하는 선언적 사용이고, C#은 키워드를 함수에 붙이면 된다.

 

공부하면서 가장 크게 느낀 차이점은 Visual studio에서는 Async를 사용하면 비동기식으로 된다고 계속 경고를 준다.

이를 동기로 사용하고 싶으면 자바의 future.get() 처럼 await을 사용하라고 한다.

 

자바는 특이하게 경고문을 주지 않고, 어노테이션 형식이라 알아서 잘 쓰라고 하는듯?

 

package com.example.async.test.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TestService {
    @Async
    public void asyncPrint(int value) {
        System.out.println("value : " + value);
    }
}

 

package com.example.async.test.controller;

import com.example.async.test.service.TestService;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    private final TestService testService;

    public TestController(TestService testService){
        this.testService = testService;
    }

    @GetMapping(value = "/test",  produces = {MediaType.APPLICATION_JSON_VALUE})
    public void test() {
        for(int i = 0; i < 1000; i++) {
            testService.asyncPrint(i);
        }
    }
}

 

 

다음은 쓰레드 동기화를 해야겠다.

'Java' 카테고리의 다른 글

자바 Async3  (0) 2020.11.08
자바 Async2  (0) 2020.11.08
자바 Callback  (0) 2020.11.03
자바 ExecutorService3(Callable)  (0) 2020.11.03
자바 newCachedThreadPool , newFixedThreadPool  (0) 2020.11.03