java的多线程run
时间: 2023-10-18 09:12:17 浏览: 41
在 Java 中,创建多线程有两种方式:继承 Thread 类或者实现 Runnable 接口。下面是实现 Runnable 接口的例子:
首先,我们定义一个实现 Runnable 接口的类:
```
public class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
```
然后,在主函数中创建一个线程并启动它:
```
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
```
在运行程序时,会创建一个新的线程并执行 MyRunnable 类中的 run() 方法。
如果你想使用继承 Thread 类的方式,可以这样做:
```
public class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
```
无论是哪种方式,都需要实现 run() 方法,该方法中包含了线程要执行的代码。线程启动后,会自动调用该方法。