Java 多线开多线程跑一个方法
在Java中,可以通过继承Thread类或者实现Runnable接口来创建多线程。以下是两种方式的示例:
- 继承Thread类的方式:
public class MyThread extends Thread {
@Override
public void run() {
// 要执行的方法
myMethod();
}
public void myMethod() {
// 你要执行的方法逻辑
}
}
// 在主线程中创建并启动多个线程
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();
thread1.start();
thread2.start();
thread3.start();
}
}
- 实现Runnable接口的方式:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 要执行的方法
myMethod();
}
public void myMethod() {
// 你要执行的方法逻辑
}
}
// 在主线程中创建并启动多个线程
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
}
}
以上两种方式都可以创建多个线程,并在每个线程中运行相同的方法。
原文地址: http://www.cveoy.top/t/topic/i6Dj 著作权归作者所有。请勿转载和采集!