익명 스레드 클래스를 시작하는 방법
다음 코드 스 니펫이 있습니다.
public class A {
public static void main(String[] arg) {
new Thread() {
public void run() {
System.out.println("blah");
}
};
}
}
여기서 start()
스레드 클래스의 인스턴스를 만들지 않고 스레드에 대한 메서드를 어떻게 호출 합니까?
당신은 이미 Thread 클래스의 인스턴스를 만들고 있습니다-당신은 그것에 대해 아무것도하지 않고 있습니다. 당신은 할 수 전화 start()
도 지역 변수를 사용하지 않고 :
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
...하지만 개인적으로 나는 일반적으로 그것을 지역 변수에 할당하고, 원하는 다른 작업 (예 : 이름 설정 등)을 한 다음 시작합니다.
Thread t = new Thread() {
public void run() {
System.out.println("blah");
}
};
t.start();
익명 클래스는 주어진 클래스를 확장하므로 변수에 저장할 수 있습니다.
예.
Thread t = new Thread()
{
public void run() {
System.out.println("blah");
}
};
t.start();
또는 즉시 만든 개체에서 시작 메서드를 호출 할 수 있습니다.
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
// similar to new Thread().start();
개인적으로는 항상 Thread 대신 Runnable의 익명 인스턴스를 만드는 것이 좋습니다. 실수로 메서드 서명이 잘못되면 컴파일러가 경고하므로 익명 클래스의 경우 익명 클래스가 정의 할 수 없기 때문에 경고합니다. 새로운 비공개 방법).
예 :
new Thread(new Runnable()
{
@Override
public void run() {
System.out.println("blah");
}
}).start();
이것이 당신이 요구하는 것인지 확실하지 않지만 다음과 같이 할 수 있습니다.
new Thread() {
public void run() {
System.out.println("blah");
}
}.start();
start()
익명 클래스의 끝에 있는 메서드를 확인하십시오. 스레드 개체를 만들지 만 실제로 실행중인 다른 스레드를 얻으려면 시작해야합니다.
익명 Thread
클래스를 만드는 것보다 익명 클래스를 만드는 것이 좋습니다 Runnable
.
new Thread(new Runnable() {
public void run() {
System.out.println("blah");
}
}).start();
대신 새 스레드에서 실행할 대상 을 삽입하는 run()
방법을 재정의합니다 . 이것은 더 나은 패턴입니다.Thread
Runnable
start ()를 호출하십시오.
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
The entire new
expression is an object reference, so methods can be invoked on it:
public class A {
public static void main(String[] arg)
{
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
}
}
Add: now you can use lambda to simplify your syntax. Requirement: Java 8+
public class A {
public static void main(String[] arg)
{
Thread th = new Thread(() -> {System.out.println("blah");});
th.start();
}
}
I'm surprised that I didn't see any mention of Java's Executor framework for this question's answers. One of the main selling points of the Executor framework is so that you don't have do deal with low level threads. Instead, you're dealing with the higher level of abstraction of ExecutorServices. So, instead of manually starting a thread, just execute the executor that wraps a Runnable. Using the single thread executor, the Runnable
instance you create will internally be wrapped and executed as a thread.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// ...
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
threadExecutor.execute(
new Runnable() {
@Override
public void run() {
System.out.println("blah");
}
}
);
} finally {
threadExecutor.shutdownNow();
}
For convenience, see the code on JDoodle.
Leaving this here for future reference, but its an answer too.
new Thread(() -> whatever()).start();
참고URL : https://stackoverflow.com/questions/9625110/how-to-start-anonymous-thread-class
'developer tip' 카테고리의 다른 글
사이트 디렉토리에 심볼릭 링크 만들기 (0) | 2020.12.10 |
---|---|
누른 버튼에서 텍스트 가져 오기 (0) | 2020.12.10 |
Editor.updateCursorPositionMz의 Meizu 장치에 대한 NullPointerException (0) | 2020.12.09 |
Win32에서 힙 손상; (0) | 2020.12.09 |
ggplot2에서 범례를 이동하거나 배치하는 방법 (0) | 2020.12.09 |