6.18 Exiting Threads and Timers
来源:互联网 发布:ubuntu 开机任务栏没了 编辑:程序博客网 时间:2024/05/16 06:16
停止线程,停止定时器
NSThread *thread= /* Get the reference to your thread here */;
[thread cancel];
NSTimer *timer= /* Get the reference to your timer here */;
[timer invalidate];
请注意在退出线程时不要用exit,因为用exit的话,线程没机会清理现场,会造成内存泄露。
不过,我还真不知道如何来调用exit,因为他是类方法,一调用就报错:No visible @interface for 'NSThread' declares the selector 'exit'
看个例子
- (void) threadEntryPoint{
@autoreleasepool {
NSLog(@"Thread Entry Point");
while ([[NSThreadcurrentThread] isCancelled] ==NO){
[NSThreadsleepForTimeInterval:4];
// if ([[NSThread currentThread] isCancelled] == NO){
NSLog(@"Thread Loop");
// }
}
NSLog(@"Thread Finished");
}
}
- (void) stopThread{
NSLog(@"Cancelling the Thread");
[self.myThreadcancel];
NSLog(@"Releasing the thread");
self.myThread =nil;
}
-(void)test6_18
{
self.myThread = [[NSThreadalloc] initWithTarget:self
selector:@selector(threadEntryPoint)
object:nil];
[selfperformSelector:@selector(stopThread)
withObject:nil
afterDelay:6.0f];
[self.myThreadstart];
}
输出:
2014-03-13 15:57:32.305 cookbook[811:360b] Thread Entry Point
2014-03-13 15:57:36.307 cookbook[811:360b] Thread Loop
2014-03-13 15:57:38.306 cookbook[811:a0b] Cancelling the Thread
2014-03-13 15:57:38.308 cookbook[811:a0b] Releasing the thread
2014-03-13 15:57:40.309 cookbook[811:360b] Thread Loop
2014-03-13 15:57:40.310 cookbook[811:360b] Thread Finished
从打印的结果可以看出,虽然线程cancel了,但是它在睡醒之后却仍然执行了一次。比较好的做法是在睡醒之后再去判断下线程是否取消了,然后在执行,如上被注释掉得那部分。
- 6.18 Exiting Threads and Timers
- Server Timers, Windows Timers, and Thread Timers的对比
- The differen between Server Timers, Windows Timers, and Thread Timers
- GAME TIMERS: ISSUES AND SOLUTIONS.
- Processes and Threads Sample
- Threads and Collections
- Processes and Threads
- Threads and Swing
- Threads and Swing
- Using threads and ProgressDialog
- Android------Process and Threads
- Processes and Threads
- Processes and Threads
- Android Processes and Threads
- Processes and Threads
- Processes and Threads
- Processes and Threads
- Processes and Threads
- android SpannableString 使用详解(给文本添加效果)
- linux之间文件传输图形界面工具gftp
- 初学opencv心得:图片拼接Stitcher函数
- codec engine工程中使用ccs下编译的lib库
- (个人总结)VC++调用Matlab生成的dll图文详解
- 6.18 Exiting Threads and Timers
- Hdu1015Safecracker(dfs)
- 达芬奇软件架构
- iOS如何将不可变变量改变成可变变量, deep copy objects into mutable
- 编程之美学习笔记2.1求二进制数中1的个数
- PAT Advanced Level 1007:Maximum Subsequence Sum
- 关于uboot.lds文件的分析
- 辨析--数组,指针
- 在知行学校感受国学古韵