将线程添加到队列

#pragma mark 简单添加一个操作到队列中
- (void)exeOperation {
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"执行了一个操作:%@", [NSThread currentThread]);
    }];
       
    NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];   
    // 一个NSOperation被添加到队列中会马上执行操作(异步执行)
    [queue addOperation:operation];
}

 

#pragma mark 添加操作到队列中
- (void)exeOperation3 {
    NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
    
    NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"执行第1个操作:%@", [NSThread currentThread]);
    }];
    
    NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"执行第2个操作:%@", [NSThread currentThread]);
    }];
    
    // 添加依赖
    [operation1 addDependency:operation2];
    
    [queue addOperation:operation1];
    [queue addOperation:operation2];
}

 

#pragma mark 添加操作到队列中
- (void)exeOperation2 {
    NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
    
    [queue addOperationWithBlock:^{
        NSLog(@"执行了第1个操作:%@", [NSThread currentThread]);
    }];
    
    [queue addOperationWithBlock:^{
        NSLog(@"执行了第2个操作:%@", [NSThread currentThread]);
    }];
    
    [queue addOperationWithBlock:^{
        NSLog(@"执行了第3个操作:%@", [NSThread currentThread]);
    }];
    
    [queue addOperationWithBlock:^{
        NSLog(@"执行了第4个操作:%@", [NSThread currentThread]);
    }];
    
    // 设置最大并发操作数量:1
    // 只允许同时开1条线程
    [queue setMaxConcurrentOperationCount:1];
}

 

posted @ 2013-05-01 17:11  wangzhenxiang  阅读(426)  评论(0编辑  收藏  举报