//多个线程并发执行  一般的时候会将多个线程放到队列中 由队列管理线程工作状态

{
    UIProgressView * progressView;
    NSOperationQueue * queue;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    progressView.frame = CGRectMake(10, 100, 300, 10);
    [self.window addSubview:progressView];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(100, 200, 100, 100);
    [button setTitle:@"线程进行" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:button];
    [self testThread];
    [self.window makeKeyAndVisible];
    return YES;
}
-(void)testThread
{
    //<1>创建队列的对象
    queue = [[NSOperationQueue alloc]init];
    //<2>设置队列中盛放的线程的最大个数
    [queue setMaxConcurrentOperationCount:4];
    //<3>队列中所有线程的优先级都是平等的
    //1、创建单独子线程
    NSInvocationOperation * test1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(threadMain1:) object:nil];
    //线程执行结束后触发下面的方法
    [test1 setCompletionBlock:^{
        NSLog(@"test1 执行结束");
    }];
    //将子线程放到队列中
    [queue addOperation:test1];
    //子线程放入队列中就会立即执行线程方法
    
    
    //2、创建block类型的线程
    NSBlockOperation * test2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0 ; i<100; i++) {
            NSLog(@"test2 i = %d",i);
            [NSThread sleepForTimeInterval:0.1];
        }
    }];
    [queue addOperation:test2];
    [test2 setCompletionBlock:^{
        NSLog(@"test2 执行结束");
        //线程结束后,会从队列中移除
    }];
}
-(void)threadMain1:(id)arg
{
    for (int i = 0 ; i<100; i++) {
        NSLog(@"test1 %d",i);
        [NSThread sleepForTimeInterval:0.1];
    }
}
-(void)buttonClick:(id)sender
{
    progressView.progress = 0;
   // [NSThread detachNewThreadSelector:@selector(threadMain:) toTarget:self withObject:nil];
    NSInvocationOperation * test3 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(threadMain:) object:nil];
    [test3 setCompletionBlock:^{
        NSLog(@"test3 结束");
    }];
}
-(void)threadMain:(id)arg
{
    for (int i = 0 ; i<100; i++) {
        [self performSelectorOnMainThread:@selector(changeThread:) withObject:@(i) waitUntilDone:NO];
        NSLog(@"progress:%f",progressView.progress);
        [NSThread sleepForTimeInterval:0.1];
    }
}
-(void)changeThread:(NSNumber *)num
{
    progressView.progress = num.intValue/100;
}

 

 
posted on 2015-07-26 17:14  火星的蝈蝈  阅读(133)  评论(0编辑  收藏  举报