Java可以通過多線程來實(shí)現(xiàn)并發(fā)。以下是一些常見的實(shí)現(xiàn)并發(fā)的方法:
class MyThread extends Thread {
public void run() {
// 線程執(zhí)行邏輯
}
}
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() {
// 線程執(zhí)行邏輯
}
}
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() {
// 任務(wù)1執(zhí)行邏輯
}
});
executor.execute(new Runnable() {
public void run() {
// 任務(wù)2執(zhí)行邏輯
}
});
executor.shutdown();
}
}
以上是三種常見的實(shí)現(xiàn)并發(fā)的方法,根據(jù)具體的需求和場景選擇最適合的方式。還有其他更高級的并發(fā)控制工具和技術(shù),例如鎖、條件變量、信號(hào)量等,可以根據(jù)需要進(jìn)一步學(xué)習(xí)和使用。