写一个Java 类用runnable接口创建并使用线程的例子
时间: 2023-04-12 10:01:00 浏览: 96
好的,以下是一个使用 Java Runnable 接口创建并使用线程的例子:
```java
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Hello from MyRunnable!");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
```
在这个例子中,我们定义了一个名为 MyRunnable 的类,它实现了 Runnable 接口。我们在 run() 方法中定义了线程要执行的任务,这里只是简单地输出一条消息。
在 main() 方法中,我们创建了一个新的线程,并将 MyRunnable 对象作为参数传递给 Thread 构造函数。然后我们调用 start() 方法来启动线程。
当我们运行这个程序时,它会输出一条消息 "Hello from MyRunnable!",这表明线程已经成功地执行了我们定义的任务。
希望这个例子能够帮助你理解如何使用 Java Runnable 接口创建并使用线程。
相关问题
java如何使用多线程,写出一个例子
Java中使用多线程可以通过继承Thread类或实现Runnable接口来实现。以下是一个使用Runnable接口的例子:
```java
public class MyRunnable implements Runnable {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + " is running.");
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}
```
以上代码中,MyRunnable类实现了Runnable接口并重写了run()方法,在run()方法中打印了当前线程的ID和正在运行的信息。在Main类中,创建了两个Thread对象,分别传入MyRunnable实例,并调用start()方法启动线程。运行该程序,可以看到两个线程交替执行run()方法。
Runnable接口可以创建线程吗
是的,Runnable接口可以用来创建线程。在Java中,线程的创建通常有两种方式:一种是继承Thread类,另一种是实现Runnable接口。这两种方式都可以用来创建线程。
实现Runnable接口的方式,通常需要将实现了Runnable接口的类作为参数传递给Thread类的构造方法,然后通过调用start()方法来启动线程。例如:
```
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
}
}
// 创建线程
Thread thread = new Thread(new MyRunnable());
// 启动线程
thread.start();
```
在这个例子中,MyRunnable类实现了Runnable接口,并重写了run()方法,run()方法中包含了线程的执行代码。在创建线程时,将MyRunnable类的实例作为参数传递给Thread类的构造方法,然后通过调用start()方法来启动线程。
需要注意的是,实现Runnable接口创建线程的方式,相比继承Thread类创建线程的方式,更加灵活和可扩展,因为一个类可以实现多个接口,而线程类却只能继承一个Thread类。同时,实现Runnable接口还可以使代码更加清晰和易于维护。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)