언제 thread.start () 대신 java의 thread.run ()을 호출하고?
언제 Java thread.run()대신 Java를 호출 thread.start()할까요?
동시성이 아닌 기능에만 관련된 특정 단위 테스트에서 ()을 호출 할 수 있습니다.
못. run ()을 직접 호출하면 일반 메소드 호출과 메소드 코드가 동 기적으로 (동일한 명령에서) 실행됩니다.
코드 스타일 자바 스레드 자주 묻는 질문 에서 가져온 것 :
Q : 메소드의 start () 메소드와 run () 메소드의 차이점은 무엇입니까?
A : 스레드 클래스의 별도 시작 () 및 실행 () 메소드는 프로그램을 작성하는 두 가지 방법을 제공합니다. start () 메서드는 새 실행을 시작하고 () 메서드를 호출합니다. start () 메소드는 즉시 리턴하고 run () 메소드가 리턴 될 때까지 새 메소드는 계속 될 것입니다.
Thread 클래스의 run () 메소드는 아무 것도 수행하지 않은 하위 클래스는 두 번째 말에서 코드로 메소드를 재정의해야합니다. Thread가 Runnable 인수로 인스턴스화되는 경우 인스턴스의 실행 () 메소드는 대신 새 공정에서 Runnable 객체를 실행합니다.
스레드 실행 () 메서드를 직접 호출하면 시작 () 메서드를 호출과 동일한 출력이 제공 될 수있는 기능을 호출하고 실행됩니다.
실행 thread.run()은 Thread코드가 실행되는 새로운 것을 만들지 언어 . thread.run()코드가 호출 된 현재 코드 에서 코드를 실행합니다.
실행 thread.start()하면 run()메소드가 호출 되는 새 OS 레벨이 작성가 작성 됩니다.
본질적으로 :
단일 단일 프로그래밍 →
run()메소드 직접 호출
멀티 메소드 프로그래밍 →
start()메소드 호출
또한 다른 사람들이 언급했듯이 '테스트'는 run()코드에서 직접 호출 할 수있는 유일한 권장 사례 인 것 입니다.
이것은 이미 암시되어 왔지만 명확합니다. run () 메소드를 호출하기 위해서만 새 스레드를 생성하는 것입니다. 그것은 실행 가능을 IMPL 등을 만들 수있는 더 나은, 더 분리 설계 어느 것이의 (a)를 호출 그것의 그 원하는 동작, 또는 (b)는 그 실행 가능을 가진 새로운 것을 생성하고 시작하면 직접 실행 ( ) 메소드를.
더 나은 분리를 위해 ExecutorJDK 5 이상에서 인터페이스와 프레임 워크를 확인하십시오 . 이로부터 분리 작업 (실행 가능한 경우)에, 간단히 실행 말해서, 당신을 허용 하는 방법 , 그것은 풀에서 기존의 단일를 사용하여, 새로운 스레드에, 현재의 스레드로 실행 가능한 실행 수 (실행 가능한 경우) 을).
전화 thread.start(), 그것은 뒤에 전화 thread.run()합니다. 우회 thread.start()하여 직접 가고 싶은 경우를 생각할 수 없습니다thread.run()
스레드 클래스 의 별도 start()및 run()메소드는 프로그램을 작성하는 두 가지 방법을 제공합니다. 이 start()메소드는 새 메소드의 실행을 시작하고 메소드를 호출합니다 run(). start()방법은 즉시 반환하고 새로운 방법은 일반적으로 계속해서 계속 run()돌아갑니다.
스레드 클래스의 run()메소드는 아무 것도 수행하지 않을 하위 클래스는 두 번째 언어에서 코드로 메소드를 재정의합니다. 단일가 Runnable 인수로 인스턴스화되는 경우의 run()메소드는 run()대신 새 도시에서 Runnable 오브젝트 의 메소드를 실행합니다 .
명령 프로그램의 경우에 따라 Thread run()메서드를 직접 호출하면 start()메서드 를 호출과 동일한 출력을 얻을 수 있습니다.
질문이 "실행 메소드 대신 시작 메소드가 직접 호출되는 이유"인 경우 아래 예제 코드로 대답했습니다. 그 희망은 명확합니다. 아래 예에서 :
/*
By calling t1.start(),
we are getting the main calling thread returned immediately
after the t1.start() called and is ready to proceed for other
operations.And the thread t1 starts executing the run method of the object r.
Hence the the output will be:
I am the main thread , i created thread t1 and had it execute run method, which is currently looping from 0 to 1000000
I am done executing run method of testThread
*/
/* If we call t1.run() instead of t1.start(), (just replace t1.start() with t1.run() in the code for testing)
its like a regular method call and the main thread will not return until the run method completes,
hence the output will be:
I am done executing run method of testThread
I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000
*/
class testThread implements Runnable{
public void run()
{
for(int i=0;i<1000000;i++){} //a simple delay block to clarify.
System.out.println("I am done executing run method of testThread");
}
}
public class mainClass{
public static void main(String [] args)
{
testThread r = new testThread();
Thread t1 = new Thread(r);
t1.start(); /* Question is: can we call instead t1.run() */
System.out.println("I am the main thread , i created thread t1 and had it execute run method, which is currently looping for i to 1000000");
}
}
동 기적으로 실행하려는 경우 메소드를 실행할 수 있습니다. 메소드를 시작 메소드를 호출하는 새 사례를 작성합니다.
다른 방법과 순서를 실행하고 ()의 순서를 실행하는 것이 좋습니다.
시작 및 실행 메소드 사용법을 알고 있다고 가정합니다. 즉, 동기 대 비동기; run 메서드는 기능을 테스트하는 데만 사용할 수 있습니다.
또한 어떤 상황에서는 하나의 실행 메소드와 다른 하나의 시작 메소드가 호출되는 두 개의 다른 객체를 사용하여 동기화 및 비동기 기능 요구 사항이있는 두 개의 다른 위치에서 동일한 스레드 클래스를 사용할 수 있습니다.
적어도 JVM 1.6에서는 약간의 검사와 실행이 기본적으로 호출됩니다.
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
private native void start0();
위의 훌륭한 주석에 대한 참고 사항 : 때때로 "start"메소드를 사용하여 다른 스레드를 실행하는 다중 스레드 코드를 작성합니다. 디버깅을 위해 "실행"( "시작 대신)"을 사용하면 코드가 동 기적으로 실행되고 디버깅이 훨씬 쉬워 지므로 훨씬 쉽게 찾을 수 있습니다.
public class TestClass implements Runnable {
public static void main(String[] args) {
TestClass tc = new TestClass();
Thread t1 = new Thread(tc);
System.out.println("Before Starting Thread " + Thread.currentThread().hashCode());
t1.start();
System.out.println("After Starting Thread " + Thread.currentThread().hashCode());
}
@Override
public void run() {
System.out.println("TestClass Run method is Running with thread " + Thread.currentThread().hashCode());
}
}
'IT' 카테고리의 다른 글
| 키 입력을 입력 할 때 UITextField의 값 가져 오기? (0) | 2020.08.06 |
|---|---|
| Chart.js v2- 격자 선 배포 (0) | 2020.08.06 |
| Hibernate Validator 4.1+에서 @NotNull, @NotEmpty 및 @NotBlank의 차이점은 무엇입니까? (0) | 2020.08.06 |
| div 내의 요소 만화하는 jQuery (0) | 2020.08.06 |
| TSQL의 COALESCE 함수 (0) | 2020.08.06 |