#import <UIKit/UIKit.h> //iOS中有三种实现多线程的方式 //1,NSThread //2,NSOperationQueue //3,GCD (grand centeral dispatch) //多线程的作用为,一款软件能够在同一时段运行多个任务 //应用程序已建立系统就给他分配一个主线程,控制手机页面 //多线程可以解决页面假死的问题 @interface LYMAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end #import "LYMAppDelegate.h" @implementation LYMAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. //页面在主线程里面,所有操作页面的过程均为操作主线程的过程 //在主线程中给页面添加UILabel UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30)]; label.backgroundColor=[UIColor redColor]; [self.window addSubview:label]; //创建子线程一 NSThread *t1=[[NSThread alloc]initWithTarget:self selector:@selector(thread1) object:nil]; //设置子线程名称 t1.name=@"thread1"; //启动子线程 [t1 start]; //创建子线程二 NSThread *t2=[[NSThread alloc]initWithTarget:self selector:@selector(thread2) object:nil]; [t2 setName:@"thread2"]; [t2 start]; //用类方法创建子线程 // NSNumber *n=[NSNumber numberWithInt:20]; NSNumber *n=@(20); [NSThread detachNewThreadSelector:@selector(thread3:) toTarget:self withObject:n]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } -(void)thread3:(id)obj { NSNumber *n=(NSNumber *)obj; for (int i=0; i<n.intValue; i++) { [NSThread sleepForTimeInterval:1]; NSLog(@"thread3"); } } -(void)thread1 { while (YES) { [NSThread sleepForTimeInterval:1]; // NSLog(@"thread1"); //获得当前方法所在的线程 NSThread *t=[NSThread currentThread]; NSLog(@"%@",t.name); } } -(void)thread2 { while (YES) { [NSThread sleepForTimeInterval:1]; NSLog(@"%@",[NSThread currentThread].name); } }
#import <UIKit/UIKit.h> @interface LYMAppDelegate : UIResponder <UIApplicationDelegate> { //线程互斥,可以将线程分隔开,以免多个线程之间相互干扰 // NSLock *_lock; NSConditionLock *_condition; } @property (strong, nonatomic) UIWindow *window; @end #import "LYMAppDelegate.h" @implementation LYMAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. // [self count]; //解决线程互斥现象 //_lock=[[NSLock alloc]init]; _condition=[[NSConditionLock alloc]init]; NSThread *t1=[[NSThread alloc]initWithTarget:self selector:@selector(count) object:nil]; t1.name=@"thread1"; [t1 start]; NSThread *t2=[[NSThread alloc]initWithTarget:self selector:@selector(count) object:nil]; t2.name=@"thread2"; [t2 start]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } int sum=0; -(void)count { while (YES) { // [_lock lock]; [_condition lock]; sum++; //获得当前子线程 NSThread *t=[NSThread currentThread]; NSLog(@"%@:%i",t.name,sum); [NSThread sleepForTimeInterval:0.9]; if (sum==10) { break; } //[_lock unlock]; [_condition unlock]; } }
#import <UIKit/UIKit.h> //通过通知中心,监听所有的子线程 @interface LYMAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end #import "LYMAppDelegate.h" @implementation LYMAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. NSThread *t1=[[NSThread alloc]initWithTarget:self selector:@selector(thread1) object:nil]; [t1 start]; //用类方法声实例化的子线程,当结束时会有[t cancel];的方法 [NSThread detachNewThreadSelector:@selector(thread2) toTarget:self withObject:nil]; //监听系统中所有子线程是否结束 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifi) name:NSThreadWillExitNotification object:nil]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } -(void)thread2 { for (int i=0; i<15; i++) { [NSThread sleepForTimeInterval:1]; NSLog(@"thread2"); } } -(void)notifi { NSLog(@"thread cancel"); } -(void)thread1 { for (int i=0; i<10; i++) { NSLog(@"thread1"); [NSThread sleepForTimeInterval:1]; } //停止当前子线程 NSThread *t=[NSThread currentThread]; [t cancel]; }
#import <UIKit/UIKit.h> @interface LYMAppDelegate : UIResponder <UIApplicationDelegate> { //创建子线程 dispatch_queue_t _queue; //调用主线程 dispatch_queue_t _main; } @property (strong, nonatomic) UIWindow *window; @end #import "LYMAppDelegate.h" @implementation LYMAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. //_queue一次创建多次使用 //给子线程赋值 _queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //给主线程赋值 _main=dispatch_get_main_queue(); //运行第一个子线程 dispatch_async(_queue, ^{ while (YES) { NSLog(@"thread1"); [NSThread sleepForTimeInterval:1]; } }); //在子线程中给主线程传参 //运行第二个子线程 dispatch_async(_queue, ^{ //下载数据 NSURL *url=[NSURL URLWithString:@"http://img.app.d1cm.com/news/img/201312021610065708.jpg"]; NSData *data=[[NSData alloc]initWithContentsOfURL:url]; UIImage *image=[[UIImage alloc]initWithData:data]; dispatch_async(_main, ^{ //将要调用主线程里面的控件 UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; imgView.image=image; [self.window addSubview:imgView]; }); }); self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }
#import "LYMAppDelegate.h" @implementation LYMAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. //创建线程队列 NSOperationQueue *queue=[[NSOperationQueue alloc]init]; //创建子线程 NSInvocationOperation *ope1=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(thread1) object:nil]; [queue addOperation:ope1]; //当线程1结束时调用该方法 [ope1 setCompletionBlock:^{ NSLog(@"thread1 over"); }]; //再创建一个子线程 NSBlockOperation *ope2=[NSBlockOperation blockOperationWithBlock:^{ // while (YES) { // NSLog(@"thread2"); // [NSThread sleepForTimeInterval:1]; // // } for (int i=0; i<5; i++) { NSLog(@"thread2"); [NSThread sleepForTimeInterval:1]; } }]; [queue addOperation:ope2]; //当线程2结束时会调用该方法 [ope2 setCompletionBlock:^{ NSLog(@"thread2 over"); }]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } -(void)thread1 { // while (YES) { // NSLog(@"thread1"); // [NSThread sleepForTimeInterval:1]; // } for (int i=0; i<5; i++) { NSLog(@"thread1"); [NSThread sleepForTimeInterval:1]; } }
#import "RootViewController.h" @interface RootViewController () @end @implementation RootViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)pressBtn:(id)sender { //在子线程中加载数据 NSThread *t=[[NSThread alloc]initWithTarget:self selector:@selector(thread1) object:nil]; [t start]; } -(void)thread1 { NSURL *url=[NSURL URLWithString:@"http://img.app.d1cm.com/news/img/201312021610065708.jpg"]; NSData *data=[[NSData alloc]initWithContentsOfURL:url]; UIImage *image=[UIImage imageWithData:data]; //将下载下来的数据运行在子线程上 [self performSelectorOnMainThread:@selector(myMainThread:) withObject:image waitUntilDone:YES]; } //页面上的控件要在主线程中访问 -(void)myMainThread:(UIImage *)img { self.imgView.image=img; } @end
#import <UIKit/UIKit.h> @interface LYMAppDelegate : UIResponder <UIApplicationDelegate> { //声明子线程也成为并行队列 dispatch_queue_t _queue; //主线程,也成为串行队列 dispatch_queue_t _main; } @property (strong, nonatomic) UIWindow *window; @end #import "LYMAppDelegate.h" @implementation LYMAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. // _queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // dispatch_async(_queue, ^{ // [self doSomething:@"A"]; // }); // // dispatch_async(_queue, ^{ // [self doSomething:@"B"]; // // }); // _main=dispatch_get_main_queue(); // dispatch_async(_main, ^{ // [self doSomething:@"A"]; // }); // dispatch_async(_main, ^{ // [self doSomething:@"B"]; // }); // [self fun1]; // [self fun2]; // [self fun3]; [self fun4]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } //该子线程会延时执行 -(void)fun4 { double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ NSLog(@"延时执行"); }); } //dispatch_once_t无论调用多少次只会调用一次 -(void)fun3 { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSLog(@"ABC"); }); dispatch_once(&onceToken, ^{ NSLog(@"BCD"); }); } //在线程组中,最后一个子线程为串行执行,其他的为并行执行 -(void)fun2 { //线程组 dispatch_group_t _t=dispatch_group_create(); dispatch_queue_t _qt=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_async(_t, _qt, ^{ [self doSomething:@"A"]; }); dispatch_group_async(_t, _qt, ^{ [self doSomething:@"B"]; }); //最后执行的线程 dispatch_group_notify(_t,_qt, ^{ [self doSomething:@"lastThread"]; }); } //自定义队列 -(void)fun1 {//DISPATCH_QUEUE_SERIAL创建串行队列 //DISPATCH_QUEUE_CONCURRENT创建并行队列 // dispatch_queue_t _t1=dispatch_queue_create("t1", DISPATCH_QUEUE_SERIAL);//串行 dispatch_queue_t _t1=dispatch_queue_create("t1", DISPATCH_QUEUE_CONCURRENT);//并行,同时可以执行多个任务 dispatch_async(_t1, ^{ [self doSomething:@"A"]; }); dispatch_async(_t1, ^{ [self doSomething:@"B"]; }); dispatch_barrier_async(_t1, ^{ NSLog(@"barrier"); }); dispatch_async(_t1, ^{ [self doSomething:@"C"]; }); dispatch_async(_t1, ^{ [self doSomething:@"D"]; }); } -(void)doSomething:(NSString *)str { NSLog(@"%@",str); [NSThread sleepForTimeInterval:1]; }