iOS NSThread

来源:互联网 发布:刷商务通软件网站 编辑:程序博客网 时间:2024/06/13 23:53

一、创建和启动线程简单说明

一个NSThread对象就代表一条线程

NSThread优点:提供了很多针对线程的方法,使用方便,轻量级 

                 缺点:关于当前线程对象的所有设置(包含线程的安全问题),全部需要开发者配置

//(id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;

    /*参数解析:

     selector :线程执行的方法,这个selector最多只能接收一个参数

     target selector消息发送的对象

     argument : 传给selector的唯一参数,也可以是nil

     */

    /*1.动态方法*/

    NSThread *thread = [[NSThreadalloc] initWithTarget:selfselector:@selector(run:)object:nil];

    /*2.静态方法*/

    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:nil];

    /*3.隐式创建线程的方法*/

    [self performSelectorInBackground:@selector(run:) withObject:nil];


    //线程命名

    thread.name =@"actionThead";

    //设置线程的优先级(0.0 - 1.01.0最高级)

    thread.threadPriority =1.0;

    //线程开始

    [thread start];

    //取消线程

    [thread cancel];

    /*判断某个线程的状态的属性

     @property (readonly, getter=isExecuting) BOOL executing;

     @property (readonly, getter=isFinished) BOOL finished;

     @property (readonly, getter=isCancelled) BOOL cancelled;

     */


    //获取当前线程信息

    [NSThreadcurrentThread];

    //获取主线程信息

    [NSThreadmainThread];

    //使当前线程暂停一段时间,或者暂停到某个时刻

    //[NSThread sleepForTimeInterval:5];

    //NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];

    //[NSThread sleepUntilDate:date];


    /*线程间的通信*/

    //1.在指定线程上执行操作

    [selfperformSelector:@selector(run)onThread:thread withObject:nilwaitUntilDone:YES];

    //2.在主线程上执行操作

    [selfperformSelectorOnMainThread:@selector(run)withObject:nilwaitUntilDone:YES];

    //3.在当前线程执行操作

    [selfperformSelector:@selector(run)withObject:nil];


0 0
原创粉丝点击