基础多线程的介绍

来源:互联网 发布:硬盘 数据恢复 价格 编辑:程序博客网 时间:2024/05/17 02:21

第一种需手动开启

1.

NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(runFor) object:nil];

[thread start];

线程需自动开启

2.

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

第二种的线程自

1.

 NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(runFor) object:nil];

NSOperationQueue *queue = [[NSOperationQueue alloc]init];

 [queue addOperation:operation];

2.

- (void)createOperation{

    NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{        

for (int i = 0; i < 10; i++) {

            NSLog(@"%d",i);

        }

        [self runFor];

    }];

    NSLog(@"NSBlockOperation == %s",__func__);

    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    [queue addOperation:block];

NSOBject自带的线程

[self performSelectorInBackground:@selector(runFor) withObject:self];

GCD主要使用

- (void)action{

//    //GCD 全名grand central dispatch

//    //并发执行的队列 DISPATCH_QUEUE_CONCURRENT

//    //还有一个同步DISPATCH_QUEUE_SERIAL

//    dispatch_queue_t concurrent = dispatch_queue_create("1", DISPATCH_QUEUE_CONCURRENT);

//    //异步执行队列,block中的代码添加到创建的队列中

//    dispatch_async(concurrent, ^{

//        for (int i = 0; i < 10; i++) {

//            NSLog(@"i == %d",i);

//        }

//    });

//   dispatch_async(concurrent, ^{

//       for (int j = 0; j < 10; j++) {

//           NSLog(@"j == %d",j);

//       }

//   });

//    

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

      

      NSURL *url = [NSURLURLWithString:@"http://img3.douban.com/view/event_poster/hlarge/public/365aa3c50b5ba01.jpg"];

     NSData *data = [NSDatadataWithContentsOfURL:url];

     UIImage *image = [UIImageimageWithData:data];

     NSLog(@"%s",__func__);

      dispatch_async(dispatch_get_main_queue(), ^{

          [self.imageViewsetImage:image];

         NSLog(@"%s",__func__);

      });


//      [self performSelectorOnMainThread:@selector(myAction:) withObject:image waitUntilDone:YES];

//      

      

  });

    

    

}



 







0 0
原创粉丝点击