NSThread/pthread

pthread和NSThread是多线程的两个使用方式,只是作为了解一下。

pthread 是C语言的,夸平台的,基本不用,这里只是简单介绍一下。

NSThread 是OC语言的,基本也不用。因为现在基本使用的是GCD和NSOperationQueue。

一、pthread

1、创建一个pthread线程

pthread_t pthread;
    //pthread_create(pthread, NULL, 函数, 传值);
    pthread_create(&pthread, NULL, run, @"gsngs");
void * run(void *p){
    for (int i = 0; i < 1000000; i++) {
        NSLog(@"current thread :%@  run -- i = %d ",[NSThread currentThread],i);
        NSLog(@"p :%@",p);
    }
    return NULL;
}

2、取消pthread线程

pthread_cancel(pthread);

 

二、NSThread

1、第一种方式开启线程 ,创建NSThread线程

//创建
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"1000m"];
    [thread start];
    //
    self.thread = thread;
-(void)run:(id)r{
    NSLog(@"thread :%@ -- r:%@",[NSThread currentThread],r);
    for (int i = 0 ; i < 50000; i++) {
        NSLog(@"i == %d   thread:%@",i ,[NSThread currentThread]);
        if ([NSThread currentThread].isCancelled) {//当线程被标记取消的时候 退出线程:查看第2部,取消线程
            [NSThread exit];
        }
    }
   
    NSLog(@"回到主线程!!!");
  //SEL: 方法 Object:值 wait:是否阻塞主线程,也就是说是否等待主线程直线完inMain:方法再继续往下执行,如果填NO就不用等待主线程直线inMain:再往下继续执行 [self performSelectorOnMainThread:@selector(inMain:) withObject:
@"回到主线程" waitUntilDone:YES];
  //继续执行 }

2、取消线程

/**
 取消
 */
- (IBAction)cancelThread:(id)sender {
    //这里的取消线程不是真正的取消线程,而是“标记”了取消线程,在线程运行的时候作为判断 查看:run:方法
    [_thread cancel];
}

 

3、第二种方式开启线程

//这种方式开启线程,得不到NSThread对象,修改相应的属性,和取消线程。
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"2000m"];

4、第三种方式开启线程

 [self performSelectorInBackground:@selector(run:) withObject:@"3000m"];

5、第四种方式开启线程,这种方式和第一种方式基本一致,不过是macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0)后才有的方法,使用block。

NSThread * thread = [[NSThread alloc]initWithBlock:^{
        NSLog(@"thread :%@",[NSThread currentThread]);
    }];
    thread.name = @"ios 10后才有的API";
    [thread start];

 

 

 

 

 

 

posted @ 2017-05-02 15:05  Gen_0  阅读(335)  评论(0编辑  收藏  举报