在Java中實現多線程的并發執行有多種方式,以下是其中的幾種常見方法:
class MyThread extends Thread {
public void run() {
// 線程執行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
class MyRunnable implements Runnable {
public void run() {
// 線程執行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable1 = new MyRunnable();
MyRunnable runnable2 = new MyRunnable();
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
thread1.start();
thread2.start();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyTask implements Runnable {
public void run() {
// 線程執行的代碼
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new MyTask());
executor.submit(new MyTask());
executor.shutdown();
}
}
無論使用哪種方式,多線程并發執行都需要注意線程安全性和數據同步的問題,避免出現并發訪問共享數據時的錯誤。可以使用synchronized關鍵字或Lock對象來實現線程之間的同步。