简体   繁体   English

Android请问接口方法在哪个线程中调用? 同步还是异步?

[英]Android does interface method called in which thread ? sync or async?

I know it is a very question. 我知道这是一个非常问题。 I am trying to implement a callback mechanism. 我正在尝试实现回调机制。

I have a java Class in Android and inside i have an interface 我在Android中有一个Java类,内部有一个接口

public interface MyInterface {

        public void cb1(Integer id);
        public void cb2(Integer id);
    };

User can use my Interface and implement, and whenever i need to inform to the user , i will invoke cb1() or cb2(). 用户可以使用我的界面并实现,每当我需要通知用户时,我都会调用cb1()或cb2()。

Question: 题:

Let's say user have provided me implementation of interface mInterface, 假设用户为我提供了接口mInterface的实现,

 while (1) {
     mInterface.cb1()
 }

1) In which thread cb1() will get invoked ? 1)将在哪个线程中调用cb1()? sync call or async call ? 同步通话还是异步通话?

2) if async call, what if the implementation of cb1() blocks for some time? 2)如果异步调用,如果cb1()的实现在一段时间内阻塞怎么办? Will all the cb1() calls delivered to the user one by one ? 将所有cb1()调用一一传递给用户吗?

In the code above it will be a synchronous call. 在上面的代码中,它将是一个同步调用。 If you want it to be async, you should create a new Thread to perform the callback on. 如果希望它是异步的,则应该创建一个新的Thread来执行回调。

Odd question. 奇怪的问题。 The code will be async relative to the main thread if it is not executed on the main thread. 如果未在主线程上执行,则代码将相对于主线程异步。 Otherwise it will be sync and is executed on the main thread 否则它将被同步并在主线程上执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 keyPressed()方法在哪个线程中调用? - In which thread is the keyPressed() method called? Android .aidl 中的 oneway 声明是否保证将在单独的线程中调用该方法? - Does oneway declaration in Android .aidl guarantee that method will be called in a separate thread? 接口实现的对象方法将被调用 - which object method of interface implementation will be called 如何找出调用方法的接口? - How to find out which interface a method was called on? 调用java Thread join()方法如何使外部线程等待应该是调用join()的线程本身? - How does calling java Thread join() method makes the outer thread to wait while it should have been the thread itself which called join()? 创建一个从MySQL返回值并在异步线程中查询的方法 - Create a method which returns value from MySQL and does query in Async thread Android服务的方法在不同的线程中调用。它仍然在主线程上运行吗? - Android service's method called in different thread. Does it still run on the main thread? class 是如何注入的,它实现了在 Java 或 Groovy 代码中调用的接口方法? - How does class gets injected which implements interface method being called in Java or Groovy code? 同步版本的异步方法 - Sync version of async method 线程内部的方法不会被调用 - method inside a thread does not get called
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM