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();
}
}
以上是三种常见的实现并发的方法,根据具体的需求和场景选择最适合的方式。还有其他更高级的并发控制工具和技术,例如锁、条件变量、信号量等,可以根据需要进一步学习和使用。