首页 > 代码库 > iOS多线程开发小demo

iOS多线程开发小demo

首先演示一下主线程的阻塞

//  DYFViewController.m//  623-01-阻塞多线程////  Created by dyf on 14-6-23.//  Copyright (c) 2014年 ___FULLUSERNAME___. All rights reserved.//#import "DYFViewController.h"@interface DYFViewController ()@end@implementation DYFViewController- (IBAction)btnOnClick {    // 1.获取当前的线程    NSThread *thread = [NSThread currentThread];        // 2.打印线程    NSLog(@"%@", thread);        // 3.执行一线耗时的操作    for (int i = 0; i < 9999; i++) {        NSLog(@"%@", thread);        // 此时点击按钮,在执行完耗时操作之前,按钮一直是高亮状态,期间用户点击其他的UI控件也不好响应    }}- (void)viewDidLoad{    [super viewDidLoad];	// Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

 容易发现,在耗时操作期间,其它UI操作都被延时了,造成用户的卡顿现象

 

--------创建子线程方法1--pthread

//  DYFViewController.m//  623-02-pthread////  Created by dyf on 14-6-23.//  Copyright (c) 2014年 ___FULLUSERNAME___. All rights reserved.//#import "DYFViewController.h"#import <pthread.h>@interface DYFViewController ()@end@implementation DYFViewController// c语言函数void *run(void *data){    // 1.获取当前的线程    NSThread *cThread = [NSThread currentThread];        // 2.打印线程    NSLog(@"%@", cThread);        // 3.h耗时操作    for (int i = 0; i < 9999; i++) {        NSLog(@"%@", cThread);    }    return NULL;}- (IBAction)btnOnClick {    // 1.获取当前的线程    NSThread *thread = [NSThread currentThread];        // 2.打印线程    NSLog(@"%@", thread);        // 3.执行一线耗时的操作 : 创建一套子线程        pthread_t threadId;    pthread_create(&threadId, NULL, *run, NULL);   }@end

 小结:此方法不常用,了解即可