Java并发编程:两个方法同时执行
在Java编程中,我们经常需要同时执行多个任务。然而,单线程程序只能按照顺序执行,无法同时执行多个任务。为了解决这个问题,Java提供了并发编程的机制,允许我们同时执行多个方法或任务。
并发编程的基本概念
在开始介绍并发编程的细节之前,先让我们了解一些基本概念。
线程
线程是操作系统能够进行运算调度的最小单位。在Java中,线程是由Thread类表示的。我们可以创建并启动多个线程来同时执行不同的任务。
并发
并发是指两个或多个任务在同一时间间隔内发生。在Java中,可以通过多线程实现并发。
并行
并行是指两个或多个任务在同一时刻发生。在Java中,可以通过多线程和多核处理器实现并行。
同步
当多个线程同时访问共享资源时,可能会导致数据不一致的问题。为了避免这种情况,我们需要使用同步机制来保证线程的安全性。
异步
异步是指任务的执行不需要等待其他任务的完成。在Java中,可以通过异步编程来实现任务的并行执行。
并发编程的实现方式
Java提供了多种方式来实现并发编程,包括使用Thread类、Runnable接口、Callable和Future接口、线程池等。
使用Thread类
Thread类是Java中表示线程的类,我们可以通过继承Thread类来创建线程。
public 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();
}
}
在上面的代码中,我们创建了两个线程对象thread1
和thread2
,并分别启动了它们。这样,两个线程会同时执行run
方法中的代码。
使用Runnable接口
除了继承Thread类,我们还可以实现Runnable接口来创建线程。
public 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();
}
}
在上面的代码中,我们创建了两个实现了Runnable接口的对象runnable1
和runnable2
,然后将它们传递给Thread类的构造方法来创建线程对象thread1
和thread2
。最后,我们启动了这两个线程。
使用Callable和Future接口
Callable接口类似于Runnable接口,但它可以返回任务的结果。Future接口表示异步计算的结果。
public class MyCallable implements Callable<Integer> {
public Integer call() {
// 返回计算结果
return 1 + 1;
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 2; i++) {
Callable<Integer> callable = new MyCallable();
Future<Integer> future = executorService.submit(callable);
futures.add(future);
}
for (Future<Integer> future : futures) {
try {
Integer result = future.get();
System.out.println("计算结果:" + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executorService.shutdown();
}
}
在上面的代码中,我们使用了ExecutorService的实现类Executors.newFixedThreadPool方法来创建一个具有两个线程的线程池。然后,我们创建了两个Callable对象callable1
和callable2
,并将它们提交给线程池来执行。最后,我们