如何解决为什么我的后台线程不运行?
| 不会从startDoingWork方法中调用doBackgroundWork方法。 threading.h
------------
#import <Foundation/Foundation.h>
@interface threading : NSObject {
NSConditionLock* theConditionLock;
NSMutableArray* workItems;
}
-(void)startDoingWork;
-(void)doBackgroundWork;
-(void)notifyBackgroundThreadAboutNewWork;
@end
threading.m
-------------
#import \"threading.h\"
enum{
workToDoNow = 1,workNotToDoNow = 0
};
@implementation threading
-(id)init{
if (self = [super init]) {
theConditionLock = [[NSConditionLock alloc]initWithCondition:workNotToDoNow];
workItems = [[NSMutableArray alloc]init];
}
return self;
}
-(void)startDoingWork{
[NSThread detachNewThreadSelector:@selector(doBackgroundWork) toTarget:self withObject:nil];
}
-(void)doBackgroundWork{
while (YES) {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc]init];
NSArray* items = nil;
NSLog(@\"Going to lock!!\");
[theConditionLock lockWhenCondition:workToDoNow];
items = [NSArray arrayWithArray:workItems];
[workItems removeAllObjects];
[theConditionLock unlockWithCondition:workNotToDoNow];
NSLog(@\"Finished the work!!\");
[pool drain];
}
}
-(void)notifyBackgroundThreadAboutNewWork{
NSLog(@\"Into the Background new work!!\");
[theConditionLock lock];
[workItems addObject:@\"Hello\"];
[theConditionLock unlockWithCondition:workToDoNow];
NSLog(@\"Finished and came out!!\");
}
@end
main.m
------
#import <Foundation/Foundation.h>
#import \"threading.h\"
int main (int argc,const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
threading* threads = [[threading alloc]init];
[threads notifyBackgroundThreadAboutNewWork];
[threads startDoingWork];
[pool drain];
return 0;
}
调试时不会调用detachNewThread:selector:toTarget:withObject方法。
解决方法
是不是您的主程序结束得如此之快,以至于后台线程没有启动的机会?您知道,即使在运行时设法建立和启动新线程之前,应用程序也已完成,并且所有线程都被杀死/关闭/无论如何。您可以使主线程休眠一秒钟,以查看后台线程是否开始运行。
, 我相信您的工作线程选择器应该只接受一个参数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。