zoukankan      html  css  js  c++  java
  • 多线程之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 }
  • 相关阅读:
    Linux系统安全及应用
    Linux 10 进程和计划的管理任务
    Centos netdata 的安装及配置
    Centos nmon安装及使用
    Python 各种数据类型的了解(上)
    神奇的循环知识
    Pathon的基础知识
    初次遇见Python
    操作系统与编程语言的简介
    计算机硬件基础
  • 原文地址:https://www.cnblogs.com/zhizunbao/p/5502602.html
Copyright © 2011-2022 走看看