移动应用程序为用户提供了使用远程服务器从remote.Connecting下载电子邮件附件的选项,并在单独的线程中下载内容。将向用户显示一个对话框,其中显示cancel command.Herewith I am providing the pseudo。
new Thread(new Runnable()
public void run(){
try{
//open connection to remote server
//get data input stream
//create byte array of length attachment size
//show modeless dialog with the message "Downloading..."
for(int i=0;i<attachmentSize;i++){
//set the progress indicator of the modeless dialog based upon for iteration
//read the byte from input stream and store it in byte array
}
//open file connection outputstream and store the downloaded content as a file in mobile file system
//show dialog with the message "attachment successfully downloaded"
}
catch(IOException ioe) { }
catch(Exception ex) { }
}
).start();现在,我正在向带有进度指示器的对话框中添加取消命令。当用户在移动端点击"Cancel“命令时,可以通过调用dispose()方法来释放无模式对话框。如何突然停止通过流式传输获取电子邮件附件的线程?请一定要帮我解决这个问题。
发布于 2009-06-20 10:52:34
你可以突然停止它--但它带来了更多值得的麻烦。
执行此操作的规范方法是在Runnable中选中一个标志:
public class ClassHoldingRunnable {
private volatile boolean stopRequested = false;
public void executeAsync() {
Runnable r= new Runnable() {
public void run() {
while ( !stopRequested ) {
// do work
}
}
}
new Thread(r).start();
}
public void cancel() {
stopRequested = true;
}
}以下是一些注意事项:
volatile或具有另一个可见性保证( synchronized、Lock、Atomic ),因为它由多个线程访问;stopRequested;<代码>H210<代码>F211发布于 2009-06-22 19:06:20
有几种方法可以中断从连接读取的线程。
发布于 2009-06-20 09:35:13
我不是这方面的专家,所以对我的建议持保留态度,因为我在Java线程方面的经验非常有限。
您不能停止正在运行的线程。您可以尽快退出它。因此,您可以做的是,例如,在辅助线程中定期测试一个共享标志。当主线程对其进行设置以响应取消单击时,辅助线程将返回。
https://stackoverflow.com/questions/1021294
复制相似问题