何时以及谁执行方法调用?

When and who executes a Method call?

我使用一个简单的方法调用来执行其他类中的方法。

当我将它与两个线程和一个 BlockingQueue 结合使用时,我问自己,哪个线程以及何时执行此调用。

我做了一个伪代码示例,其实用处不大,但描述了案例:

线程 A

public class ThreadA extends Thread {
  private static final String TAG = "ThreadA";

  @Override
  public void run() {

    ThreadB threadB = new ThreadB();
    threadB.start();
    InputStream InPut = null;//Imagen this inputStream results out of any kind 
                             //of connection (Bluetooth,...)
    byte[] buffer = new byte[1024];

    while (true){
      try {
        InPut.read(buffer);
        threadB.send(buffer+"");
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

线程 B

public class ThreadB extends Thread {
  private static final String TAG = "ThreadB";

  private BlockingQueue<String> queue = new LinkedBlockingQueue<>();

  @Override
  public void run() {
    while (true){
      String st ="";
      try {
        st = queue.take();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      Log.d(TAG, "String is: " + st);
    }
  }
    

  public void send(String a) {
    queue.add(a);
  }
}

Szenario:当线程 B 在 .take() 中被阻塞但方法被调用时,这是如何工作的?

我的问题是观察到的,当我使用它时,线程 A 中的输入流读取了错误的数据。

threadB.send(buffer+"");

我假设您对此次通话感到困惑。这是线程A调用的方法。

要从总体上理解这一点,您需要区分线程 Java 对象和实际的 OS 线程。 Java线程对象不是"real"线程,它们只是线程的代表。

如果在线程对象上调用 start(),它会创建一个新的 "real" OS 线程,其中 运行 是 运行() 方法。您在此类线程对象上调用的其他方法,如 join(),是您在当前线程上调用的方法,但会触发与 "real" 线程交互的 OS 系统调用。你调用的Thread子类中有一个方法与执行它的线程无关,它始终是当前线程。