您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在 Java 中,线程间的协作可以通过以下几种方式实现:
共享变量:通过在多个线程之间共享一个或多个变量,可以让线程相互影响彼此的执行。为了确保数据的一致性,可以使用 synchronized 关键字或者 java.util.concurrent 包中的类(如 ReentrantLock、AtomicInteger 等)来同步访问共享资源。
等待/通知机制:Java 提供了 wait() 和 notify() 方法,用于线程间的协作。当一个线程调用某个对象的 wait() 方法时,它会释放该对象的锁并进入等待状态。另一个线程调用相同对象的 notify() 方法时,会将等待状态的线程唤醒。这种机制通常与 synchronized 关键字一起使用。
示例:
class SharedResource {
synchronized void waitForSignal() throws InterruptedException {
wait(); // 当前线程进入等待状态
}
synchronized void sendSignal() {
notify(); // 唤醒等待状态的线程
}
}
示例:
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
new Thread(() -> {
try {
String item = queue.take(); // 获取队列中的元素,若队列为空则等待
System.out.println("Received: " + item);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
queue.put("Hello"); // 向队列中添加元素,若队列已满则等待
System.out.println("Sent: Hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
示例:
import java.util.concurrent.Semaphore;
class SharedResource {
private final Semaphore semaphore = new Semaphore(3); // 最多允许 3 个线程同时访问
void doSomething() throws InterruptedException {
semaphore.acquire(); // 获取信号量,若信号量为零则等待
try {
// 执行操作
} finally {
semaphore.release(); // 释放信号量
}
}
}
示例:
import java.util.concurrent.CountDownLatch;
class WorkerThread extends Thread {
private final CountDownLatch latch;
public WorkerThread(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
// 执行操作
} finally {
latch.countDown(); // 完成操作后减少计数器
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
int numberOfThreads = 5;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
new WorkerThread(latch).start();
}
latch.await(); // 等待所有线程完成操作
System.out.println("All threads have finished.");
}
}
这些方法可以根据具体需求组合使用,以实现线程间的协作。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。