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 Thread class and uses the start() method to initiate the thread.
  • Option B: This code snippet implements the Runnable interface and creates a separate Thread object using the Runnable instance, which is then started with the start() method.
  • Option C: This code snippet demonstrates the use of an anonymous inner class implementing Runnable to create a thread.
  • Option D: This snippet contains the syntax error mentioned above, making it the incorrect implementation. The main method should be defined outside the run() method. The semicolon after t.start() is also missing.
Java Thread Implementation: Identifying the Incorrect Code Snippet

原文地址: https://www.cveoy.top/t/topic/oz0W 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录