zoukankan      html  css  js  c++  java
  • 多线程(一) NSThread

    OS中多线程的实现方案:

    技术 语言 线程生命周期 使用频率
    pthread C 程序员自行管理 几乎不用
    NSthread OC 程序员自行管理 偶尔使用
    GCD C 自动管理 经常使用
    NSOperation OC 自动管理 经常使用

    线程的状态

    NSThread的创建方式:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    //创建线程方式一
    NSThread *threadOne = [[NSThread alloc] initWithTarget:self selector:@selector(testAction) object:nil];
    //给线程命名
    threadOne.name = @"threadOne";
    //启动线程,在新开的线程执行testAction方法
    [threadOne start];
     
    //创建线程方式二,并且会自动启动
    [NSThread detachNewThreadSelector:@selector(testAction) toTarget:self withObject:nil];
     
    //创建线程方式三,隐式创建方式,自动启动
    [self performSelectorInBackground:@selector(testAction) withObject:nil];

     调用的方法

    1
    2
    3
    4
    5
    6
    7
    - (void)testAction
    {
        for (int i = 0; i < 3; i++)
        {
            NSLog(@"i = %d,当前线程 = %@",i,[NSThread currentThread]);
        }
    }

    结果:可以看到有3条线程并发执行

     

    线程的属性:

    1
    2
    3
    4
    5
    6
    //创建一个线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(testAction) object:nil];
    //线程名字
    thread.name = @"wl";
    //线程优先级,一般情况不设置,默认0.5,数值范围0-1,数值越大优先级越高
    thread.threadPriority = 0.5;

    常用方法,这些都是类方法,相对于这段代码所在的线程进行操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    //获得主线程
    [NSThread mainThread];
    //判断是否为主线程,返回一个BOOL值
    BOOL isMainThread = [NSThread isMainThread];
    //判断是否为多线程,返回一个BOOL值
    BOOL isMultiThreaded = [NSThread isMultiThreaded];
    //把线程从可调度线程池中移除2s(阻塞线程)
    [NSThread sleepForTimeInterval:2];
    //把线程从可调度线程池中移除直到一个时间点(阻塞线程)
    [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
    //停止线程,线程死亡,这个线程就已经不存在了
    [NSThread exit];
     
  • 相关阅读:
    python 入门
    element 使用问题总结
    element dialog 弹窗 解决每次先加载上一次数据再加载本次数据问题
    JS 对变量进行全文替换方法
    react源码解析10.commit阶段
    react源码解析9.diff算法
    react源码解析8.render阶段
    react源码解析7.Fiber架构
    react源码解析6.legacy模式和concurrent模式
    react源码解析5.jsx&核心api
  • 原文地址:https://www.cnblogs.com/luoxiaofu/p/5250143.html
Copyright © 2011-2022 走看看