Java并发包下常用类介绍
在Java中,有许多常用的并发包类。以下是一些常用的类及其用法和示例:
1. ReentrantLock
ReentrantLock是一个可重入的互斥锁。它的作用类似于synchronized关键字,但是它提供了更多的灵活性和功能。
下面是一个简单的示例,演示了如何在两个线程之间使用ReentrantLock来控制访问:
import java.util.concurrent.locks.ReentrantLock;
public class MyThread implements Runnable {
private final ReentrantLock lock = new ReentrantLock();
public void run() {
lock.lock();
try {
// Do some work
} finally {
lock.unlock();
}
}
}
2. Semaphore
Semaphore是一种基于计数器的同步工具,用于控制对共享资源的访问。它可以用来限制并发线程的数量。
下面是一个示例,演示了如何使用Semaphore来控制对某个资源的访问:
import java.util.concurrent.Semaphore;
public class MyResource {
private final Semaphore semaphore = new Semaphore(1);
public void useResource() {
try {
semaphore.acquire();
// Do some work
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
3. CountDownLatch
CountDownLatch是一个同步工具,允许一个或多个线程等待其他线程完成操作。
下面是一个示例,演示了如何使用CountDownLatch来协调多个线程的操作:
import java.util.concurrent.CountDownLatch;
public class MyThread implements Runnable {
private final CountDownLatch latch;
public MyThread(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
// Do some work
latch.countDown();
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
int n = 10;
CountDownLatch latch = new CountDownLatch(n);
for (int i = 0; i < n; i++) {
Thread t = new Thread(new MyThread(latch));
t.start();
}
latch.await();
// All threads have finished
}
}
4. Executor
Executor是一个接口,用于管理线程池。它提供了一种更高级别的抽象,让我们可以将任务提交给线程池,而不用关心线程管理的细节。
下面是一个示例,演示了如何使用Executor来创建并管理线程池:
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MyThread implements Runnable {
public void run() {
// Do some work
}
}
public class Main {
public static void main(String[] args) {
Executor executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
executor.execute(new MyThread());
}
}
}
5. Future
Future是一个接口,用于表示异步计算的结果。它可以用来在后台执行任务,并在将来的某个时候获取任务的结果。
下面是一个示例,演示了如何使用Future来执行异步任务并获取其结果:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class MyCallable implements Callable<String> {
public String call() {
// Do some work
return "Result";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<String> callable = new MyCallable();
FutureTask<String> futureTask = new FutureTask<>(callable);
Thread t = new Thread(futureTask);
t.start();
String result = futureTask.get();
System.out.println(result);
}
}
这些是Java并发包中的一些常用类和示例。希望这篇文章能帮助你更好地理解Java中的并发编程。如果你想了解更多关于Java并发编程的知识,请继续阅读其他的文章和教程。