Java Thread Implementation: Identifying the Incorrect Code Snippet
Jerry wants to implement a thread object. Which of the following code snippets is incorrect?
A
class InfoManage extends Thread {
public static void main(String[] args) {
InfoManage im = new InfoManage();
im.start();
}
}
B
class InfoManage implements Runnable {
@Override
public void run() {
System.out.println('running');
}
public static void main(String[] args) {
InfoManage im = new InfoManage();
im.start();
}
}
C
class InfoManage {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println('running');
}
});
t.start();
}
}
D
class InfoManage implements Runnable {
@Override
public void run() {
System.out.println('running');
public static void main(String[] args) {
InfoManage im = new InfoManage();
Thread t = new Thread(im);
t.start();
}
}
Answer: D
The run() method in option D has a syntax error. There is a missing semicolon after the t.start() statement, and the main method is incorrectly placed inside the run() method.
Explanation:
- Option A: This code snippet correctly extends the
Threadclass and uses thestart()method to initiate the thread. - Option B: This code snippet implements the
Runnableinterface and creates a separateThreadobject using theRunnableinstance, which is then started with thestart()method. - Option C: This code snippet demonstrates the use of an anonymous inner class implementing
Runnableto create a thread. - Option D: This snippet contains the syntax error mentioned above, making it the incorrect implementation. The
mainmethod should be defined outside therun()method. The semicolon aftert.start()is also missing.
原文地址: https://www.cveoy.top/t/topic/oz0W 著作权归作者所有。请勿转载和采集!