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;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Runnable() {
public void run() {
// 任務1執行邏輯
}
});
executor.execute(new Runnable() {
public void run() {
// 任務2執行邏輯
}
});
executor.shutdown();
}
}
以上是三種常見的實現并發的方法,根據具體的需求和場景選擇最適合的方式。還有其他更高級的并發控制工具和技術,例如鎖、條件變量、信號量等,可以根據需要進一步學習和使用。