当前位置: 移动技术网 > IT编程>开发语言>Java > Java异步处理机制实例详解

Java异步处理机制实例详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

       通常同步意味着一个任务的某个处理过程会对多个线程在用串行化处理,而异步则意味着某个处理过程可以允许多个线程同时处理。下面我们就来看看有关异步处理的详细内容。

       异步通常代表着更好的性能,因为它很大程度上依赖于缓冲,是典型的使用空间换时间的做法,例如在计算机当中,高速缓存作为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();
 }

}

总结

以上就是本文关于异步机制的全部内容,实例代码中的注释还是比较详细的,如果有什么问题可以留言,小编会及时回复大家。同时也感谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网