zoukankan      html  css  js  c++  java
  • 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];
  • 相关阅读:
    小内存 linux 主机部署 mysql
    IIS enable HTTP PUT and DELETE
    使用Topshelf部署.net core windows服务 Demo
    Windows Template Studio 创建 .net core wpf应用
    vue笔记——vue生命周期
    (转)idea如何快速查看接口的实现类
    vue项目设置启动自动打开浏览器
    批量添加题目功能(正则表达式的使用案例)
    markdown的diff效果
    SVN提交时取消某个文件的提交
  • 原文地址:https://www.cnblogs.com/qq9070/p/6796186.html
Copyright © 2011-2022 走看看