当前位置: 移动技术网 > IT编程>开发语言>Java > java 同步、异步、阻塞和非阻塞分析

java 同步、异步、阻塞和非阻塞分析

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

java 同步、异步、阻塞和非阻塞分析

概要:

正常情况下,我们的程序以同步非阻塞的方式在运行。但是我们的程序总会出现一些耗时操作,比如复杂的计算(找出1到10亿之间的素数)和程序本身无法控制的操作(io操作、网络请求)。包含这些耗时操作的方法我们可以把它称为阻塞方法,包含这些耗时操作的任务我们可以把它称为阻塞任务。阻塞与非阻塞是以是否耗时来定义的。

如果程序中存在大量阻塞操作,就会影响程序性能。但是阻塞的存在是客观事实,我们的程序是无法改变它的,一个网络请求需要3秒才能响应,我们不可能让它1毫秒就能响应,因为接受请求的服务器可能完全不由我们控制。但是我们可以改变处理阻塞的方式——以异步的方式处理阻塞任务。实现异步的主要技术就是多线程。图示:

同步和异步是个时序概念。同步就是同时只执行一个任务,而异步则是同时执行多个任务。

代码示例

模拟网络请求:



package com.zzj.asyn; 
 
public class httprequest { 
  private callable callable; 
   
  public httprequest(callable callable) { 
    this.callable = callable; 
  } 
   
  public void send(){ 
    // 模拟网络请求 
    try { 
      thread.sleep(1000 * 5); 
    } catch (interruptedexception e) { 
      e.printstacktrace(); 
      thread.currentthread().interrupt(); 
    } 
    // 回调 
    this.callable.call("hello world!"); 
  } 
   
  public interface callable{ 
    void call(string result); 
  } 
} 

以同步方式处理阻塞任务:

package com.zzj.asyn; 
 
import com.zzj.asyn.httprequest.callable; 
 
/** 
 * 以同步的方式处理阻塞任务 
 * @author lenovo 
 * 
 */ 
public class app { 
  public static void main(string[] args) { 
    new httprequest(new callable() { 
      @override 
      public void call(string result) { 
        system.out.println("thread:" + thread.currentthread().getname()); 
        system.out.println("message from remote server:" + result); 
      } 
    }).send(); 
    system.out.println("thread " + thread.currentthread().getname() + " is over!"); 
  } 
} 

结果:

thread:main 
message from remote server:hello world! 
thread main is over! 

以异步的方式处理阻塞任务:

package com.zzj.asyn; 
 
import com.zzj.asyn.httprequest.callable; 
 
/** 
 * 以异步的方式处理阻塞任务 
 * @author lenovo 
 * 
 */ 
public class app2 { 
  public static void main(string[] args) { 
    new thread(new runnable() { 
      @override 
      public void run() { 
        new httprequest(new callable() { 
          @override 
          public void call(string result) { 
            system.out.println("thread:" + thread.currentthread().getname()); 
            system.out.println("message from remote server:" + result); 
          } 
        }).send(); 
      } 
    }).start(); 
    system.out.println("thread " + thread.currentthread().getname() + " is over!"); 
  } 
} 

结果:

thread main is over! 
thread:thread-0 
message from remote server:hello world! 

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

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

相关文章:

验证码:
移动技术网