• 多线程(二)--NSThread基本使用


    iOS多线程实现方案

    pthread:
    C语言,生命周期需要管理,
    一套通用多线程API
    试用UnixLinuxWindows系统
    跨平台可移植
    使用难度大

    NSThread:
    OC语言,生命周期需要管理
    面向对象
    可直接操作线程对象

    GCD:(常用)
    C语言,自动管理生命周期
    旨在替代NSThread等多线程技术
    充分利用设备多核

    NSOperation:(常用)
    OC语言,自动管理线程生命周期
    基于GCD
    比GCD多些简单实用功能
    更面向对象


    举例:
    pthread

    #import <pthread.h>

    void *run(void *data)
    {
    for (int i = 0; i<10000; i++) {
    NSLog(@"touchesBegan----%d-----%@", i, [NSThread currentThread]);
    }
    return NULL;
    }

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
    // 创建线程
    pthread_t myRestrict;
    pthread_create(&myRestrict, NULL, run, NULL);
    }


    NSThread:

    一个NSThread对象代表一条线程
    创建、启动线程

    NSThread *current = [NSThread currentThread];

    线程调度优先级
    + (double)threadPriority;
    + (BOOL)setThreadPriority:(double)p;
    - (double)threadPriority;
    - (BOOL)setThreadPriority:(double)p;
    优先级范围:0.0~1.0
    默认0.5
    值越大优先级越高

    线程名称
    - (void)setName:(NSString *)n;
    - (NSString *)name;

    3种创建线程方式

    /**
    * 创建线程的方式3
    */

    - (void)createThread3

    {
    // 这2个不会创建线程,在当前线程中执行
    // [self performSelector:@selector(download:) withObject:@"http://c.gif"];
    // [self download:@"http://c.gif"];

    [self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
    }


    /**
    * 创建线程的方式2
    */

    - (void)createThread2
    {
    [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
    }


    /**
    * 创建线程的方式1
    */

    - (void)createThread1
    {
    // 创建线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://b.png"];
    thread.name = @"下载线程";

    // 启动线程(调用self的download方法)
    [thread start];
    }

    - (void)download:(NSString *)url

    {
    NSLog(@"下载东西---%@---%@", url, [NSThread currentThread]);
    }


    线程睡眠(阻塞线程)
    // 睡眠5秒钟

    [NSThread sleepForTimeInterval:5];

    // 3秒后的时间
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];

    [NSThread sleepUntilDate:date];


    启动线程
    - (void)start;
    就绪--运行--执行完毕死亡

    阻塞(暂停)线程
    + (void)sleepUntilDate:(NSDate *)date;
    + (void)sleepForTimeInterval:(NSTimeInterval)ti;
    进入阻塞状态

    强制停止线程
    + (void)exit;

    线程死了之后,不可以重新start

  • 相关阅读:
    14.5.5 Creating a File-Per-Table Tablespace Outside the Data Directory
    14.5.5 Creating a File-Per-Table Tablespace Outside the Data Directory
    php session 管理
    php session 管理
    CURD特性
    RabbitMQ学习总结(1)——基础概念详细介绍
    RabbitMQ学习总结(1)——基础概念详细介绍
    RabbitMQ学习总结(1)——基础概念详细介绍
    Java基础学习总结(39)——Log4j 1使用教程
    Java基础学习总结(39)——Log4j 1使用教程
  • 原文地址:https://www.cnblogs.com/fangchun/p/4684327.html
Copyright © 2020-2023  润新知