“`
第一种方法
- (IBAction)didClick:(id)sender {
// NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@selector(calculate) object:nil];
开启子线程
// [thread start];
// 第二种
[NSThread detachNewThreadSelector:@selector(calculate) toTarget:self withObject:nil];
}
//在子线程中执行
-(void)calculate
{
// 在子线程里面执行的事件 创建对象时可能会用到便利构造器,这时占用的内存释放不掉,所以和主线程一样在外面加一个自动释放池
@autoreleasepool {
NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@”%d”,[NSThread isMainThread]);
}];
[operation start];
int a= 0;
for (int i = 1; i <= 355;i ++) {
[self performSelectorOnMainThread:@selector(test:) withObject:[NSString stringWithFormat:@”%d”,a] waitUntilDone:YES];
a += i;
}
}
}
//
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
// NSBlockOperation * block = [NSBlockOperation blockOperationWithBlock:^{
//
// [[NSThread currentThread]setName:@”11”];
// NSLog(@”你是我的小丫小苹果我玩玩水水水水谁谁谁水水水水%@”,[NSThread currentThread]);
// }];
// NSBlockOperation * block2 = [NSBlockOperation blockOperationWithBlock:^{
// NSLog(@”该吃饭了(⊙o⊙)哦”);
// }];
//
// [queue addOperation:block];
// [queue addOperation:block2];
//
最大并发数.所谓的最大并发数指的是同时执行的任务个数。如果最大并发数设置为1,可以实现多线程下的线程同步
// queue.maxConcurrentOperationCount = 1;
//
// 可以设置有几个子线程
// [self performSelectorInBackground:@selector(background:) withObject:@”