Java 线程没有运行完成,为什么?
我有一个 Runnable,通过在其 run 方法中执行以下操作,将数据(几百个文件)从 Android 设备传输到 PC
- 创建一个进程并使用 Runtime.exec(CMD) 执行命令
- 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
- Creates a process and executes a command using Runtime.exec(CMD)
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用命令的输出。
此问题展示了如何使用 shell 脚本而不是代码中的输出:Java ProcessBuilder:结果进程挂起。
如果您想在 Java 代码中使用输出,基本上您将从 Process.InputStream 提供的 InputStream 中读取。
这会阻塞,直到其他进程完成。如果您想要并发,您可以在另一个线程中读取输出。
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.
This blocks until the other process is complete. If you wanted concurrency, you could read the output in a another thread.