zoukankan      html  css  js  c++  java
  • 多线程的创建方法

    - (void)viewDidLoad {
        [super viewDidLoad];
       

        //第一种开启新的线程调用 mutableTheard
        NSThread * t = [[NSThread alloc]initWithTarget:self selector:@selector(mutableTheard) object:nil];
        [t start];
        
        
        //第二种开启新的线程调用 mutableTheard
        [NSThread detachNewThreadSelector:@selector(mutableTheard) toTarget:self withObject:nil];
        
        //第三种开新的线程 mutableTheard
        [self performSelectorInBackground:@selector(mutableTheard) withObject:self];
        
        //第四种开新的线程
        NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
        [operationQueue addOperationWithBlock:^{
            for (int i = 1; i <100; i++) {
                NSLog(@"---多线程");
            }
        }];

        
        //第五种开新的线程
        NSOperationQueue * Queue = [[NSOperationQueue alloc]init];
        //设置线程执行的并发数。
        Queue.maxConcurrentOperationCount = 2;
        //创建一个线程惭怍对象
        NSInvocationOperation * operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(mutableTheard) object:nil];
       //创建一个线程惭怍对象
        NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(mutableTheard) object:nil];
        //把线程添加到队列中
        [operationQueue  addOperation:operation1];
        [operationQueue addOperation:operation2];
        
        
        
        //第六种开新的线程GCD
        dispatch_queue_t queue = dispatch_queue_create("test", NULL);
        dispatch_async(queue, ^{
            NSLog(@"我在多线程");
        });
        
        //可以使用这个方法可以回到主线程
        dispatch_sync(dispatch_get_main_queue(), ^{
            BOOL isMain = [NSThread isMainThread];
            if (isMain == YES) {
           NSLog(@"回到主线程了");
            }
            
        });
        
        
        //用过这种方法,还是同步在当前线程上
        dispatch_sync(queue, ^{
            ///当前线程
        });
        
        
    }


    -(void)mutableTheard
    {
    ///创建自动释放池
        @autoreleasepool {
         
            
         [self  performSelectorOnMainThread:@selector(mainTheard) withObject:nil waitUntilDone:YES];// 回到主线程
            

        }
     }
     

     
  • 相关阅读:
    爬虫 爬取糗事百科热门板块的信息
    爬虫 爬取豆瓣高分电影信息
    django model之Meta选项
    ubuntu下无法获得锁 /var/lib/apt/lists/lock – open (11: 资源暂时不可用)
    django 通过数据库表名获取app名
    JS自定义字符串格式化函数
    django 制作上传图片并预览的效果
    Django序列化
    Django以ajax方式提交form
    Manjaro20 Linux安装VS Code
  • 原文地址:https://www.cnblogs.com/canghaixiaoyuer/p/4561434.html
Copyright © 2011-2022 走看看