Java me 当用户触发取消命令时停止线程
移动应用程序为用户提供了从远程下载电子邮件附件的选项。与远程服务器连接并下载内容是在单独的线程中执行的。使用“取消”命令会向用户显示一个对话框。在此,我提供了伪代码Java me 当用户触发取消命令时停止线程,java-me,Java Me,移动应用程序为用户提供了从远程下载电子邮件附件的选项。与远程服务器连接并下载内容是在单独的线程中执行的。使用“取消”命令会向用户显示一个对话框。在此,我提供了伪代码 new Thread(new Runnable() public void run(){ try{ //open connection to remote server //get data input stream //create byte array of length attac
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();
new线程(new Runnable())
公开募捐{
试一试{
//打开到远程服务器的连接
//获取数据输入流
//创建长度为附件大小的字节数组
//显示带有消息“正在下载…”的无模式对话框
对于(inti=0;i我不是这方面的专家,所以对我的建议持保留态度,因为我在Java线程方面的经验非常有限
您无法停止正在运行的线程。您可以尽快退出它。因此,您可以做的是,例如,在次线程中定期测试一个共享标志。当主线程响应取消单击设置它时,次线程将返回。您可以突然停止它,但它会带来更多的麻烦这是值得的
执行此操作的标准方法是在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;
}
}
请注意:
- stopRequested标志必须是易变的,或者具有另一个可见性保证(
synchronized
,Lock
,Atomic
),因为它被多个线程访问
- 如果最终用户需要一个响应性GUI,那么您应该经常检查
stopRequested
我的经验更多的是C语言,但这可能仍然适用
我不认为找到一种“杀死线程”的方法是一个好主意,就像你只是删除一个对象并跳过它的析构函数一样
您可以通过中断告诉线程自杀。然后,您可以使用线程的中断标志作为指示器,或者,如果您在其中有睡眠/等待,您可以捕获中断的异常,并在捕获时正确关闭(在finally块中)。这应该或多或少地提供您正在寻找的内容。有几种方法可以中断从连接读取的线程
- 您可能通过对InputStream.read的单个调用来读取远程数据,因此可以重用单个相对较小的字节[]对象。您可以在每次迭代之前检查布尔成员变量。您实际上不需要围绕该布尔值进行同步,因为它在线程构造之后只需要更改一次值
- 关闭连接意味着您的线程在下一次尝试访问它时将抛出IOException。正确的JavaME实现将不会创建Connection.close()块,即使另一个线程正在读取连接的InputStream