定义一个类实现Runnable接口实现线程应用,该线程实现1-10的输出
时间: 2024-03-27 14:41:38 浏览: 18
好的,下面是实现代码:
```java
public class CountThread implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
CountThread countThread = new CountThread();
Thread thread = new Thread(countThread);
thread.start();
}
}
```
这里我们定义了一个名为`CountThread`的类,实现了`Runnable`接口,重写了`run()`方法,在`run()`方法中循环输出1-10的数字。在`main()`方法中,我们创建了一个新的线程,将`CountThread`对象作为参数传入,然后启动该线程。当运行该程序时,将输出1-10的数字。
相关问题
实现runnable接口定义线程重载run()
当一个类实现了 Runnable 接口,就必须重写 run() 方法,这个方法定义了线程的入口点,也就是线程要执行的代码。可以通过以下步骤来实现:
1. 创建一个类并实现 Runnable 接口。
2. 重写 run() 方法,定义线程要执行的代码。
3. 创建 Thread 对象,并将实现了 Runnable 接口的类作为参数传递给 Thread 构造函数。
4. 调用 Thread 对象的 start() 方法启动线程。
示例代码如下:
```
public class MyRunnable implements Runnable {
public void run() {
// 线程要执行的代码
System.out.println("Thread is running.");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
```
在上面的示例中,我们创建了一个实现了 Runnable 接口的类 MyRunnable,并重写了 run() 方法。在 main() 方法中,我们创建了一个 Thread 对象,并将 MyRunnable 对象作为参数传递给了 Thread 构造函数。最后,调用了 Thread 对象的 start() 方法启动线程。
自定义一个类Demo2,使其实现Runnable接口。
好的,下面是一个实现 Runnable 接口的自定义类 Demo2 的示例代码:
```php
class Demo2 implements Runnable {
public function run() {
for ($i = 1; $i <= 10; $i++) {
echo '线程执行中:' . $i . "\n";
sleep(1);
}
}
}
```
在上面的代码中,我们定义了一个名为 Demo2 的类,并实现了 Runnable 接口。Runnable 接口是一个标准接口,它包含一个 run() 方法,该方法用于定义线程执行的逻辑。在 Demo2 类中,我们重写了 run() 方法,并添加了一个简单的循环,用于输出线程执行的计数器值。在每次循环中,线程会休眠一秒钟,以便我们观察线程的执行情况。
当我们想要创建一个新线程时,可以通过实例化 Demo2 类并将其作为参数传递给 Thread 类的构造函数。例如:
```php
$demo2 = new Demo2();
$thread = new Thread($demo2);
$thread->start();
```
在上面的代码中,我们首先实例化 Demo2 类并将其赋值给 $demo2 变量,然后将 $demo2 变量作为参数传递给 Thread 类的构造函数。最后,我们启动新线程并开始执行 run() 方法。