首页 > 试题广场 >

下面两个类, 想在第二个类里面启动第一个类的线程,

[单选题]
下面两个类, 想在第二个类里面启动第一个类的线程,在第15行应该怎样做?( )1public class Century implements Runnable {
2public void run () {
3for (int year = 1900;year < 2000;year++) {
4System.out.println(year);
5try {Thread.sleep(1000);
6} catch(InterruptedException e) {}
7}
8System.out.println("Happy new millenium!");
9}
10}
11
12class CountUp {
13public static void main (String [] args) {
14Century ourCentury = new Century();
15
16   }
17 }
  • Thread t = new Thread(this);  t.start();
  • Thread t = new Thread(this);        t.start(ourCentury);
  • Thread t = new Thread(this);        ourCentury.run();
  • Thread t = new Thread(ourCentury);        t.start();

Java 提供了三种创建线程的方法:

  • 通过实现 Runnable 接口;
  • 通过继承 Thread 类本身;
  • 通过 Callable 和 Future 创建线程。

介绍Runable使用

Thread 定义了几个构造方法,下面的这个是我们经常使用的:
Thread(Runnable threadObj,String threadName);
这里,threadOb 是一个实现 Runnable 接口的类的实例,并且 threadName 指定新线程的名字。


编辑于 2021-09-03 08:30:27 回复(0)
1. 首先分析选项A和B: - 在 CountUp 类的 main 方法中, this 指的是 CountUp 类的当前实例,而不是 Century 类的实例,所以 Thread t = new Thread(this); 是错误的。因此A和B选项错误。 2. 接着看选项C: - 直接调用 ourCentury.run() 只是在当前线程中执行 Century 类的 run 方法,并没有启动一个新的线程。所以C错误。 3. 最后看选项D: - 要启动一个实现了 Runnable 接口的类的线程,需要创建一个 Thread 对象,将 Runnable 实例作为参数传入,然后调用 start 方法。 Century 类实现了 Runnable 接口, ourCentury 是 Century 类的一个实例,所以 Thread t = new Thread(ourCentury); t.start(); 是正确的做法。所以D正确。 答案是D。
发表于 2024-10-30 19:23:48 回复(0)