Java에서 별도의 스레드로 메서드를 호출하는 방법은 무엇입니까?
방법이 있다고 가정 해 봅시다 doWork()
. 메인 스레드가 아닌 별도의 스레드에서 어떻게 호출합니까?
Runnable
인터페이스 를 구현하는 클래스를 만듭니다 . 실행하려는 코드를 run()
메소드 에 넣으십시오 Runnable
. 이것이 인터페이스 를 준수하기 위해 작성해야하는 메소드입니다 . "기본"스레드에서 새 Thread
클래스를 만들고 생성자에의 인스턴스를 전달한 Runnable
다음 호출 start()
합니다. start
JVM에게 새 스레드를 만드는 마법을 수행 한 다음 run
해당 새 스레드에서 메서드 를 호출하도록 지시합니다 .
public class MyRunnable implements Runnable {
private int var;
public MyRunnable(int var) {
this.var = var;
}
public void run() {
// code in the other thread, can reference "var" variable
}
}
public class MainThreadClass {
public static void main(String args[]) {
MyRunnable myRunnable = new MyRunnable(10);
Thread t = new Thread(myRunnable)
t.start();
}
}
시작하려면 Java의 동시성 자습서 를 살펴보십시오 .
메서드가 자주 호출되는 경우 비용이 많이 드는 작업이므로 매번 새 스레드를 생성 할 가치가 없습니다. 일종의 스레드 풀을 사용하는 것이 가장 좋습니다. 한 번 봐 가지고 Future
, Callable
, Executor
에서 클래스 java.util.concurrent
패키지를.
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// code goes here.
}
});
t1.start();
또는
new Thread(new Runnable() {
@Override
public void run() {
// code goes here.
}
}).start();
또는
new Thread(() -> {
// code goes here.
}).start();
또는
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
myCustomMethod();
}
});
또는
Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
myCustomMethod();
}
});
Java 8에서는 한 줄의 코드로이를 수행 할 수 있습니다.
메서드가 매개 변수를 사용하지 않는 경우 메서드 참조를 사용할 수 있습니다.
new Thread(MyClass::doWork).start();
그렇지 않으면 람다 식에서 메서드를 호출 할 수 있습니다.
new Thread(() -> doWork(someParam)).start();
사물을 호출하는 또 다른 빠른 옵션 (예 : DialogBoxes 및 MessageBoxes 및 스레드가 아닌 메서드를위한 별도의 스레드 생성)은 Lamba 표현식을 사용하는 것입니다.
new Thread(() -> {
"code here"
}).start();
Sometime ago, I had written a simple utility class that uses JDK5 executor service and executes specific processes in the background. Since doWork() typically would have a void return value, you may want to use this utility class to execute it in the background.
See this article where I had documented this utility.
To achieve this with RxJava 2.x you can use:
Completable.fromAction(this::dowork).subscribeOn(Schedulers.io().subscribe();
The subscribeOn()
method specifies which scheduler to run the action on - RxJava has several predefined schedulers, including Schedulers.io()
which has a thread pool intended for I/O operations, and Schedulers.computation()
which is intended for CPU intensive operations.
If you are using at least Java 8 you can use method runAsync
from class CompletableFuture
CompletableFuture.runAsync(() -> {...});
If you need to return a result use supplyAsync
instead
CompletableFuture.supplyAsync(() -> 1);
참고URL : https://stackoverflow.com/questions/3489543/how-to-call-a-method-with-a-separate-thread-in-java
'program story' 카테고리의 다른 글
자바 코드에서 "loop :". (0) | 2020.08.08 |
---|---|
R을 사용하여 데이터 프레임 행을 조건부로 제거 (0) | 2020.08.08 |
목록 확인 방법 (0) | 2020.08.08 |
문서 폴더의 파일 목록 가져 오기 (0) | 2020.08.08 |
앱이 실행되는 동안 Android 비활성화 화면 시간 초과 (0) | 2020.08.08 |