Home  >  Article  >  Java  >  What does java asynchronous mean?

What does java asynchronous mean?

(*-*)浩
(*-*)浩Original
2019-05-21 17:43:4710276browse

This article will introduce Java asynchronous, I hope it will be helpful to everyone.

What does java asynchronous mean?

Asynchronous: Asynchronous is the opposite of synchronous. When an asynchronous procedure call is issued, the caller You can continue to perform subsequent operations before getting results.

That is to say, no matter how long it takes for the asynchronous method to execute the code, it has no impact on the main thread, and the main thread can continue to execute downwards.

For example: a water pipe with forks, the fork is the asynchronous call entrance.

Port A is the main thread and port B is the auxiliary thread. When something blocks port B, it does not affect the flow of water to port A.

What does java asynchronous mean?

Define callback interface

After the asynchronous code is executed, the results often require some processing,
So define a Interface, used to handle asynchronous results.

/**
 * 定义回调接口
 * @author YZQ
 *
 */
public interface MyCallback {

	/**
	* 定义处理回调方法
	* @param object
	*/
	void callback(Object object);
}

Define asynchronous implementation class

 /**
 * 异步任务类
 * @author YZQ
 *
 */
public class AsynTask {

	/**
	* 处理任务
	* @param myCallback 处理完任务后的回调
	*/
	public void task(final MyCallback myCallback){
		Thread thread=new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
				    //线程睡眠3秒,模拟该线程执行时间过长,也就是上面说的【B口有东西塞住】
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				//完成0到99的累加
				int sum=0;
				for(int i=0;i<p><strong>Test:</strong><br></p><pre class="brush:php;toolbar:false">/**
 * 测试类
 * @author YZQ
 *
 */
public class Test {

	public static void main(String[] args) {
		//调用异步任务
		new AsynTask().task(new MyCallback() {
		    //实现回调方法
			@Override
			public void callback(Object object) {
				System.out.println("异步回调处理:值 "+object);
			}
		});
		
		System.out.println("主线程等待异步输出");
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

What does java asynchronous mean?

It can be seen:
The main thread first outputs [Main thread waits for asynchronous output],
Then the auxiliary thread outputs [Asynchronous callback processing: value 4950].

Related learning recommendations: java basic tutorial

The above is the detailed content of What does java asynchronous mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:what is java2Next article:what is java2