Java 异步处理的简单实践
最编程
2024-07-16 15:37:11
...
同步与异步
通常同步意味着一个任务的某个处理过程会对多个线程在用串行化处理,而异步则意味着某个处理过程可以允许多个线程同时处理。
异步通常代表着更好的性能,因为它很大程度上依赖于缓冲,是典型的使用空间换时间的做法,例如在计算机当中,高速缓存作为cpu和磁盘io之间的缓冲地带协调cpu高速计算能力和磁盘的低速读写能力。
volatile
应用场景:检查一个应用执行关闭或中断状态。因为此关键字拒绝了虚拟对一个变量多次赋值时的优化从而保证了虚拟机一定会检查被该关键字修饰的变量的状态变化。
CountDownLatch
应用场景:控制在一组线程操作执行完成之前当前线程一直处于等待。例如在主线程中执行await()方法阻塞主线程,在工作线程执行完逻辑后执行countDown()方法。
本文示例场景:
1,从控制台发送消息到消息服务器(由一个队列模拟)。
2,将消息队列写入到文件(对写文件的操作设置延时以模拟性能瓶颈)。
3,消息服务器作为控制台和文件写入之间的缓冲区。
示例代码:
注:往消息队列添加消息可以通过for循环一次性加入,本文为了便于观察文件和队列的变化而采用了控制台输入,实际写一行文件记录速度应该高于手速,所以本文示例中增加了线程sleep时间。
package org.wit.ff.ch2; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * * <pre> * 简单异步处理示例. * </pre> * * @author F.Fang * @version $Id: AsyncHandler.java, v 0.1 2014年10月23日 下午11:37:54 F.Fang Exp $ */ public class AsyncHandler { /** * 控制资源释放. */ private CountDownLatch latch; /** * 处理完成标识. */ private volatile boolean handleFinish; /** * 消息写入本地文件完成. */ private volatile boolean sendFinish; /** * 阻塞队列. */ private BlockingQueue<String> queue; private BufferedWriter bw; public AsyncHandler(CountDownLatch latch) { this.latch = latch; /** * 使用链表实现. */ queue = new LinkedBlockingQueue<String>(); File file = new File("E:/hello.txt"); try { bw = new BufferedWriter(new FileWriter(file)); } catch (IOException e) { throw new RuntimeException(e); } } public void handle() { // 模拟性能瓶颈的执行过程,3s处理一条消息. new Thread() { public void run() { while (!handleFinish) { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e1) { // 不做处理. } String s = queue.peek(); if (s != null) { queue.poll(); try { bw.write(s); bw.newLine(); } catch (IOException e) { } } // 若队列为空并且消息发送完成. if (queue.isEmpty() && sendFinish) { // 计数器1->0 latch.countDown(); // 让处理过程结束. handleFinish = true; break; } } } }.start(); } /** * * <pre> * 给出消息发送完成的标识. * </pre> * */ public void sendFinish() { sendFinish = true; } /** * * <pre> * 资源释放. * </pre> * */ public void release() { System.out.println("release!"); if (bw != null) { try { bw.close(); } catch (IOException e) { // TODO 打印日志. } } //其实使用queue = null就够了. if (queue != null) { queue.clear(); queue = null; } } /** * * <pre> * 往队列发送消息. * </pre> * * @param text */ public void sendMsg(String text) { if (text != null && !text.isEmpty()) { queue.add(text); } } public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(1); AsyncHandler handler = new AsyncHandler(latch); handler.handle(); // 做一次检查. Scanner scanner = new Scanner(System.in); while (true) { String text = scanner.next(); // 若用户选择退出. if ("exit".equals(text)) { // 表示消息已经发送完成. handler.sendFinish(); break; } handler.sendMsg(text); } try { // 阻塞主线程等待消息写入到本地文件完成. latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } // 释放资源 文件流,队列. handler.release(); // 关闭控制台输入. scanner.close(); } }
推荐阅读
-
Java 项目实践 II 基于 Java + Spring Boot + MySQL 的匹配网站设计与实施(源代码 + 数据库 + 文档)
-
在 ts 中实现类 java hashmap 的简单方法
-
@SneakyThrows:简化 Java 异常处理的好工具
-
数据库构建平台架构的最佳实践|用于海量数据存储和处理的分布式数据库|数据库架构的演变
-
原型模式的设计模式(简单易懂--代码帮助理解[Java 版本)
-
Java 中的异常和错误:深入了解异常处理
-
Java 中的五种 I/O 模式详解--五、异步 I/O(Asynchronous I/O)
-
【Java编程】用简单的100行代码实现2048小游戏
-
Java 8新特性探究(十三)JavaFX 8新特性以及开发2048游戏-JavaFX历史## 跟java在服务器端和web端成绩相比,桌面一直是java的软肋,于是Sun公司在2008年推出JavaFX,弥补桌面软件的缺陷,请看下图JavaFX一路走过来的改进 从上图看出,一开始推出时候,开发者需使用一种名为JavaFX Script的静态的、声明式的编程语言来开发JavaFX应用程序。因为JavaFX Script将会被编译为Java bytecode,程序员可以使用Java代码代替。 JavaFX 2.0之后的版本摒弃了JavaFX Script语言,而作为一个Java API来使用。因此使用JavaFX平台实现的应用程序将直接通过标准Java代码来实现。 JavaFX 2.0 包含非常丰富的 UI 控件、图形和多媒体特性用于简化可视化应用的开发,WebView可直接在应用中嵌入网页;另外 2.0 版本允许使用 FXML 进行 UI 定义,这是一个脚本化基于 XML 的标识语言。 从JDK 7u6开始,JavaFx就与JDK捆绑在一起了,JavaFX团队称,下一个版本将是8.0,目前所有的工作都已经围绕8.0库进行。这是因为JavaFX将捆绑在Java 8中,因此该团队决定跳过几个版本号,迎头赶上Java 8。 ##JavaFx8的新特性 ## ###全新现代主题:Modena 新的Modena主题来替换原来的Caspian主题。不过在Application的start方法中,可以通过setUserAgentStylesheet(STYLESHEET_CASPIAN)来继续使用Caspian主题。 参考http://fxexperience.com/2013/03/modena-theme-update/ ###JavaFX 3D 在JavaFX8中提供了3D图像处理API,包括Shape3D (Box, Cylinder, MeshView, Sphere子类),SubScene, Material, PickResult, LightBase (AmbientLight 和PointLight子类),SceneAntialiasing等。Camera类也得到了更新。从JavaDoc中可以找到更多信息。 ###富文本 强化了富文本的支持 ###TreeTableView ###日期控件DatePicker 增加日期控件 ###用于 CSS 结构的公共 API
-
实现和简单分析java中的几种排序算法