Thread t = new Thread(this);
时间: 2024-05-23 17:14:23 浏览: 7
这是一个创建线程的语句,将当前对象作为参数传递给Thread构造函数,表示新线程将运行当前对象的run()方法。其中this指的是当前对象,如果在类中使用该语句,就表示当前类实现了Runnable接口,并且该语句出现在实现了run()方法的类中。创建线程后,调用start()方法启动线程,执行run()方法中的代码。
相关问题
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();
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.
thread_ = new std::thread(&AppDemo::run, this);
thread_ = new std::thread(&AppDemo::run, this); 是一个创建线程的语句,它使用了C++标准库中的std::thread类来创建一个新的线程,并将AppDemo类的run函数作为线程的入口点。this指针表示当前对象的地址,通过将this指针传递给std::thread构造函数,可以在新线程中调用AppDemo类的成员函数run。
这段代码的作用是在AppDemo类的对象上创建一个新的线程,并在该线程中执行run函数。通过使用多线程,可以实现并发执行,提高程序的性能和响应能力。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)