Given: class Century implements Runnable { public void run() { for ( int year = 1900; year < 2000; year++ ) { System.out.println(year); try { Thread.sleep(1000); } catch (InterruptedException e) { } } System.out.println(“Happy new millennium!”); } } public class CountUp { public static void main(String[] args) { Century ourCentury = new Century(); // put your line here } } There’s a missing line in CountUp.main(), which is to begin the thread defined in Century. Which is the proper code: A. Thread t = new Thread(this); t.start(); B. Thread t = new Thread(ourCentury); ourCentury.start(); C. Thread t = new Thread(this); t.start(ourCentur); D. Thread t = new Thread(ourCentury); t.start();
时间: 2024-02-14 22:05:06 浏览: 94
The proper code to begin the thread defined in Century is option D:
```
Thread t = new Thread(ourCentury);
t.start();
```
Explanation:
- Option A (`Thread t = new Thread(this); t.start();`) won't work because `this` refers to the `CountUp` class, which does not implement the `Runnable` interface.
- Option B (`Thread t = new Thread(ourCentury); ourCentury.start();`) won't work because `start()` is not a method of the `Century` class (it's a method of the `Thread` class).
- Option C (`Thread t = new Thread(this); t.start(ourCentury);`) won't work because the `start()` method does not take any arguments.
Option D is correct because it creates a new `Thread` object (`t`) and passes the `Century` object (`ourCentury`) as an argument to the `Thread` constructor. Then it starts the thread using the `start()` method of the `Thread` object.
阅读全文