在Java中实现多线程主要有以下几种方法:
public class MyThread extends Thread {
@Override
public void run() {
// 线程执行的任务
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的任务
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 线程执行的任务
}
});
thread.start();
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
// 线程执行的任务
}
});
}
executor.shutdown();
}
}
以上就是Java中实现多线程的几种方法,具体选择哪种方法取决于具体的需求和场景。