
在java应用程序开发中,我们经常会遇到这样的场景:一个类(例如,执行文件拷贝操作的类)在运行时不断更新某个数据(如已拷贝的字节数或进度百分比),而另一个类(例如,用户界面或日志记录类)需要实时获取并显示这些更新。这种跨类、跨线程的数据同步需求,是构建响应式和可监控应用的关键挑战。本文将深入探讨如何高效、安全地实现java中不同运行类之间的变量共享和实时进度追踪。
当一个变量在某个类中被持续修改,而另一个类需要同步读取其最新值时,核心挑战在于如何确保数据的一致性、可见性,尤其是在涉及多线程并发操作时。简单的静态变量访问可能不足以应对所有情况,因为Java内存模型(JMM)可能导致一个线程对变量的修改对另一个线程不可见,或者在读取时出现竞态条件。因此,我们需要采用更健壮的设计模式和并发控制机制。
观察者模式是一种行为设计模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。在进度追踪场景中,执行任务的类是“主题”(Subject),而显示进度的类是“观察者”(Observer)。
概念: 生产者(执行任务的类)持有观察者实例,并在数据更新时主动调用观察者的方法来通知其变化。
实现:
立即学习“Java免费学习笔记(深入)”;
代码示例:
// 1. 观察者接口
interface ProgressObserver {
void updateProgress(int current, int total);
}
// 2. 具体的观察者类,用于显示进度
class ConsoleProgressObserver implements ProgressObserver {
@Override
public void updateProgress(int current, int total) {
System.out.println("当前进度: " + current + "/" + total);
}
}
// 3. 执行任务的生产者类
class FileCopier {
private final int totalBlocks;
private ProgressObserver observer; // 可以是List<ProgressObserver>支持多个观察者
public FileCopier(int totalBlocks, ProgressObserver observer) {
this.totalBlocks = totalBlocks;
this.observer = observer;
}
public void startCopying() {
System.out.println("文件拷贝开始...");
for (int currentBlock = 1; currentBlock <= totalBlocks; currentBlock++) {
// 模拟文件拷贝操作
try {
Thread.sleep(100); // 模拟耗时操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("拷贝中断");
return;
}
// 每次更新后通知观察者
if (observer != null) {
observer.updateProgress(currentBlock, totalBlocks);
}
}
System.out.println("文件拷贝完成!");
}
}
// 测试类
public class ObserverPatternDemo {
public static void main(String[] args) {
// 创建观察者
ProgressObserver observer = new ConsoleProgressObserver();
// 创建文件拷贝器,并注册观察者
FileCopier copier = new FileCopier(50, observer);
// 启动拷贝任务
copier.startCopying();
}
}优缺点:
轮询模式与观察者模式相反,它不依赖于主动通知,而是由消费者定期向生产者请求最新数据。
概念: 消费者(进度显示类)主动定期从生产者(任务执行类)获取数据。
实现:
立即学习“Java免费学习笔记(深入)”;
代码示例:
// 1. 执行任务的生产者类
class TaskExecutor {
public final int totalSteps;
private volatile int currentStep = 0; // 使用volatile确保可见性
public TaskExecutor(int totalSteps) {
this.totalSteps = totalSteps;
}
public void executeTask() {
System.out.println("任务执行开始...");
for (int i = 1; i <= totalSteps; i++) {
try {
Thread.sleep(150); // 模拟耗时操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("任务中断");
return;
}
currentStep = i; // 更新当前步骤
}
System.out.println("任务执行完成!");
}
public int getCurrentStep() {
return currentStep;
}
public boolean isCompleted() {
return currentStep >= totalSteps;
}
}
// 2. 进度显示消费者类
class ProgressMonitor {
private TaskExecutor executor;
public ProgressMonitor(TaskExecutor executor) {
this.executor = executor;
}
public void startMonitoring() {
System.out.println("开始监控进度...");
while (!executor.isCompleted()) {
System.out.println("当前进度: " + executor.getCurrentStep() + "/" + executor.totalSteps);
try {
Thread.sleep(500); // 每500毫秒轮询一次
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("监控中断");
break;
}
}
System.out.println("最终进度: " + executor.getCurrentStep() + "/" + executor.totalSteps);
System.out.println("监控结束.");
}
}
// 测试类
public class PollingPatternDemo {
public static void main(String[] args) {
TaskExecutor executor = new TaskExecutor(30);
ProgressMonitor monitor = new ProgressMonitor(executor);
// 在单独的线程中执行任务,以便监控器可以同时轮询
new Thread(executor::executeTask).start();
// 在主线程中启动监控器
monitor.startMonitoring();
}
}优缺点:
当任务和进度显示需要在不同的线程中并行运行时,直接通过共享变量进行通信是一种常见且高效的方法。但这种方式必须严格遵守并发编程的最佳实践,以确保线程安全。
概念: 两个或多个线程通过访问同一个共享内存位置(变量)来交换信息。一个线程更新变量,另一个线程读取变量。
实现:
立即学习“Java免费学习笔记(深入)”;
代码示例 (使用 AtomicLong 确保线程安全):
import java.util.concurrent.atomic.AtomicLong;
// 1. 任务执行类,更新共享的进度变量
class ConcurrentTaskProducer {
private final long totalItems;
private final AtomicLong processedItems = new AtomicLong(0); // 使用AtomicLong确保原子性和可见性
public ConcurrentTaskProducer(long totalItems) {
this.totalItems = totalItems;
}
public void startProcessing() {
System.out.println("任务生产者启动...");
for (long i = 1; i <= totalItems; i++) {
try {
Thread.sleep(50); // 模拟处理单个项目
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("生产者中断");
return;
}
processedItems.incrementAndGet(); // 原子性地增加计数
}
System.out.println("任务生产者完成.");
}
public long getProcessedItems() {
return processedItems.get();
}
public long getTotalItems() {
return totalItems;
}
public boolean isFinished() {
return processedItems.get() >= totalItems;
}
}
// 2. 进度显示类,在单独线程中读取共享变量
class ConcurrentProgressConsumer {
private final ConcurrentTaskProducer producer;
public ConcurrentProgressConsumer(ConcurrentTaskProducer producer) {
this.producer = producer;
}
public void startMonitoring() {
System.out.println("进度消费者启动...");
while (!producer.isFinished()) {
long current = producer.getProcessedItems();
long total = producer.getTotalItems();
System.out.println("实时进度: " + current + "/" + total + " (" + String.format("%.2f", (double)current / total * 100) + "%)");
try {
Thread.sleep(200); // 每200毫秒读取一次
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("消费者中断");
break;
}
}
System.out.println("最终实时进度: " + producer.getProcessedItems() + "/" + producer.getTotalItems());
System.out.println("进度消费者完成.");
}
}
// 测试类
public class SharedVariableDemo {
public static void main(String[] args) {
ConcurrentTaskProducer producer = new ConcurrentTaskProducer(200);
ConcurrentProgressConsumer consumer = new ConcurrentProgressConsumer(producer);
// 生产者和消费者在不同的线程中运行
Thread producerThread = new Thread(producer::startProcessing);
Thread consumerThread = new Thread(consumer::startMonitoring);
producerThread.start();
consumerThread.start();
// 等待两个线程完成
try {
producerThread.join();
consumerThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("主线程等待中断");
}
System.out.println("所有任务完成。");
}
}优缺点:
在选择和实现类间数据共享方案时,应考虑以下几点:
在Java中实现不同运行类之间的变量共享和实时进度追踪,有多种有效的设计模式和技术。观察者模式适用于生产者主动通知消费者的场景,提供高实时性和松耦合。轮询模式则赋予消费者更大的控制权,但可能牺牲部分实时性。当涉及并发操作时,通过共享变量进行通信是高效的选择,但前提是必须严格遵循线程安全原则,并合理运用volatile、Atomic类或synchronized等并发控制机制。根据具体的应用需求、对实时性的要求以及并发复杂性,选择最合适的方案,并结合最佳实践,才能构建出健壮、高效且易于维护的Java应用程序。
以上就是Java类间变量共享与进度追踪教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号