iOS使用NSOperation创建线程

来源:互联网 发布:调查问卷数据怎么统计 编辑:程序博客网 时间:2024/05/16 08:15

- (IBAction)nsop1:(id)sender {

    //使用NSOperationQueue可以用depend非常方便的控制线程之间的执行顺序

    NSOperationQueue *q=[[NSOperationQueuealloc] init];

    [q addOperationWithBlock:^{

        

       int x=0;

       while (x<20) {

           NSLog(@"%@",[NSThreadcurrentThread]);

            [NSThreadsleepForTimeInterval:2];

           //多线程间参数传递

            [selfperformSelector:@selector(showInfo:)onThread:[NSThreadmainThread] withObject:@"create-queue dispathc-syn"waitUntilDone:NO];

            x++;

        }

        

   

        

    }];

}

- (IBAction)nsop2:(id)sender {

    NSBlockOperation *b1=[[NSBlockOperationalloc]init];

    [b1 addExecutionBlock:^{

        NSLog(@"test NSBlockOperation %@",[NSThreadcurrentThread]);

        

    }];

    NSBlockOperation *b2=[NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"test BSBlockOperation blockOperationWithBlock!  %@",[NSThreadcurrentThread]);

    }];

    NSOperationQueue *q=[[NSOperationQueuealloc] init];

    [qaddOperation:b1];

    [qaddOperation:b2];

}

- (IBAction)nsop3:(id)sender {

    NSBlockOperation *b1=[[NSBlockOperationalloc]init];

    [b1 addExecutionBlock:^{

        NSLog(@"test NSBlockOperation %@",[NSThreadcurrentThread]);

        

    }];

    NSBlockOperation *b2=[NSBlockOperationblockOperationWithBlock:^{

        NSLog(@"test BSBlockOperation blockOperationWithBlock!  %@",[NSThreadcurrentThread]);

    }];

    NSOperationQueue *q=[[NSOperationQueuealloc] init];

    q.maxConcurrentOperationCount=4;

    [b1addDependency:b2];

    [qaddOperation:b1];

    [qaddOperation:b2];


}

0 0