在Java中實現(xiàn)多線程主要有以下幾種方法:
public class MyThread extends Thread {
@Override
public void run() {
// 線程執(zhí)行的任務(wù)
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// 線程執(zhí)行的任務(wù)
}
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() {
// 線程執(zhí)行的任務(wù)
}
});
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() {
// 線程執(zhí)行的任務(wù)
}
});
}
executor.shutdown();
}
}
以上就是Java中實現(xiàn)多線程的幾種方法,具體選擇哪種方法取決于具體的需求和場景。