多线程之NSThread和NSObject

 1 #pragma mark - NSThread实现多线程
 2     /*
 3     // 获取当前线程
 4     NSLog(@"currentThread = %@", [NSThread currentThread]);
 5     
 6     
 7     // 获取主线程
 8     NSLog(@"mainThread = %@", [NSThread mainThread]);
 9     
10     
11     // 判断当前线程是否为主线程
12     NSLog(@"isMainThread = %d", [NSThread isMainThread]);
13     */
 1 #pragma mark - NSThread手动开辟子线程
 2     /*
 3     // 参数1:target
 4     // 参数2:方法
 5     // 参数3:传参
 6     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(sayHi) object:nil];
 7     
 8     // 让线程开启
 9     [thread start];
10     
11     // 使用NSThread和NSObject实现的开辟线程,系统会自动释放,不用自己关闭线程,写不写都行
12     // 结束线程的两种方式:
13     // 方式一:取消线程
14     [thread cancel];    // 不是真正的说取消就取消,而是给线程发送一个信号,通过这个信号进行取消的
15     
16     // 方式二:直接将线程退出
17     [NSThread exit];
18     */
1 #pragma mark - NSThread自动开辟子线程
2     /*
3     // 线程自动开启
4     // 把手动开辟的target和selector两个参数顺序反着来
5     [NSThread detachNewThreadSelector:@selector(sayHi) toTarget:self withObject:nil];
6     */
 1 #pragma mark - NSObject开启子线程
 2     
 3     // 使用performSelectorInBackground开辟子线程
 4     // 第一个参数:selector
 5     // 第二个参数:方法传递的参数
 6     [self performSelectorInBackground:@selector(sayHi) withObject:@"test"];
 7     
 8     self.view.backgroundColor = [UIColor yellowColor];
 9 }
10 
11 
12 - (void)sayHi {
13     
14     // 回到主线程修改背景颜色
15     // 参数1:selector
16     // 参数2:传参
17     // 参数3:是否等到子线程的任务完成之后进入主线程
18     [self performSelectorOnMainThread:@selector(mainThreadChangeColor) withObject:nil waitUntilDone:YES];
19 }
20 
21 
22 - (void)mainThreadChangeColor {
23     
24     self.view.backgroundColor = [UIColor lightGrayColor];
25     
26     NSLog(@"%@", [NSThread currentThread]);
27     NSLog(@"%@", [NSThread mainThread]);
28 }

 

转载于:https://www.cnblogs.com/zhizunbao/p/5502602.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值