Java 线程没有运行完成,为什么?

发布于 2024-10-17 21:59:42 字数 358 浏览 5 评论 0原文

我有一个 Runnable,通过在其 run 方法中执行以下操作,将数据(几百个文件)从 Android 设备传输到 PC

  1. 创建一个进程并使用 Runtime.exec(CMD) 执行命令
  2. CMD 是传输数据的命令从设备到运行该线程的 PC。 (这是 android 的 adb pull 命令)

我有一个主程序,它创建一个线程并启动这个可运行的程序。可运行程序开始运行,它执行“adb pull”命令并开始传输数据,但它似乎在完成完整传输之前不久就暂停了。如果我强制退出主程序,传输就会完成。

另外,如果我从主程序本身执行命令而不使用另一个线程,我不会遇到任何问题。

为什么我会面临这个问题?

I have a Runnable that transfers data(a few hundred files) from an android device to a PC by doing the following in its run method

  1. Creates a process and executes a command using Runtime.exec(CMD)
  2. The CMD is a command that transfers data from a device to the PC that runs this thread.
    (This is an adb pull command for android )

I have a main program that creates a Thread and starts this runnable. The runnable starts running and it executes the "adb pull" command and starts transferring the data, BUT it seems to pause soon after before it completes the full transfer. IF I force quit the main program, the transfer runs to completion.

Also had I executed the command from the main program itself without using another thread, I face no issues.

Why am I facing this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2024-10-24 21:59:42

您需要使用命令的输出。

此问题展示了如何使用 shell 脚本而不是代码中的输出:Java ProcessBuilder:结果进程挂起

如果您想在 Java 代码中使用输出,基本上您将从 Process.InputStream 提供的 InputStream 中读取。

   Process process = Runtime.exec(CMD);
   InputStream in = process.getInputStream();
   // Repeatedly read from the input stream until eof.

这会阻塞,直到其他进程完成。如果您想要并发,您可以在另一个线程中读取输出。

You need to consume the output of the command.

This question shows how to consume the output in shell scripts rather than your code: Java ProcessBuilder: Resultant Process Hangs .

If you want to consume the output in your Java code, basically you'll read from InputStream provided by Process.InputStream.

   Process process = Runtime.exec(CMD);
   InputStream in = process.getInputStream();
   // Repeatedly read from the input stream until eof.

This blocks until the other process is complete. If you wanted concurrency, you could read the output in a another thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文