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];// 回到主线程
            

        }
     }
     

     
  • 相关阅读:
    Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.
    Spring NoSuchBeanDefinitionException六大原因总结
    深入分析Spring 与 Spring MVC容器
    MyBatis mapper parameterType
    eclipse下的mybatis插件:MyBatipse
    javax.servlet-api 和 servlet-api 区别
    Spring中ClassPathXmlApplication与FileSystemXmlApplicationContext的区别
    dump总结
    操作系统基础知识
    JMM中的Happens-Before原则
  • 原文地址:https://www.cnblogs.com/canghaixiaoyuer/p/4561434.html
Copyright © 2011-2022 走看看