How to Start a Thread in Java: The Correct Way to Initialize 'MyThread'
The correct way to start the 'MyThread' thread is:
public class MyThread extends Thread {
public void run() { ... }
}
A. new MyThread().start();
Explanation:
Option A is the correct way to start a thread. The start() method does the following:
- Creates a new thread: It creates a new thread object for the
MyThreadclass. - Calls the
run()method: It invokes therun()method of theMyThreadclass in a separate thread of execution.
Why not the other options?
- B. None of the above: This is incorrect; option A is correct.
- C.
new MyThread().run();: This would simply execute therun()method in the current thread, not creating a new thread. This is not multithreading. - D.
new MyThread().sleep();: This would put the thread to sleep, but it wouldn't start the thread in the first place.
原文地址: https://www.cveoy.top/t/topic/odT0 著作权归作者所有。请勿转载和采集!