iOS多线程

来源:互联网 发布:尔雅网络课大学语文 编辑:程序博客网 时间:2024/05/21 19:43

#import <UIKit/UIKit.h>

#import "MyNSOperation.h"

@interface RootViewController :UIViewController

{

   NSInteger ticKetCount;

}

@end

//************************************************************//

#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {

   [superviewDidLoad];

   //初始化票数为10

   ticKetCount =10;

   UILabel *lable = [[UILabelalloc] initWithFrame:CGRectMake(150,5, 150,20)];

   lable.text =@"线程";

   lable.textColor = [UIColorwhiteColor];

   lable.font = [UIFontsystemFontOfSize:20];

   lable.textAlignment =NSTextAlignmentCenter;

   [self.viewaddSubview: lable];

   self.navigationItem.titleView = lable;

   UIButton *button = [UIButtonbuttonWithType:UIButtonTypeCustom];

   button.frame =CGRectMake(50,50, 200,50);

   [button setTitle:@"阻塞主线程"forState:UIControlStateNormal];

   [button addTarget:selfaction:@selector(blockMainThread)forControlEvents:UIControlEventTouchUpInside];

   button.backgroundColor = [UIColorblackColor];

   button.showsTouchWhenHighlighted =YES;

   [self.viewaddSubview: button];

   UIButton *button1 = [UIButtonbuttonWithType:UIButtonTypeCustom];

   button1.frame =CGRectMake(50,110, 200,50);

   [button1 setTitle:@"NSObject"forState:UIControlStateNormal];

   [button1 addTarget:selfaction:@selector(touchNSobjectButton)forControlEvents:UIControlEventTouchUpInside];

   button1.backgroundColor = [UIColorblackColor];

   button1.showsTouchWhenHighlighted =YES;

   [self.viewaddSubview: button1];

   UIButton *button2 = [UIButtonbuttonWithType:UIButtonTypeCustom];

   button2.frame =CGRectMake(50,170, 200,50);

   [button2 setTitle:@"NSthread"forState:UIControlStateNormal];

   [button2 addTarget:selfaction:@selector(touchNSthreadButton)forControlEvents:UIControlEventTouchUpInside];

   button2.backgroundColor = [UIColorblackColor];

   button2.showsTouchWhenHighlighted =YES;

   [self.viewaddSubview: button2];

   UIButton *button3 = [UIButtonbuttonWithType:UIButtonTypeCustom];

   button3.frame =CGRectMake(50,230, 200,50);

   [button3 setTitle:@"子线程下载图片"forState:UIControlStateNormal];

   [button3 addTarget:selfaction:@selector(downLoadButton)forControlEvents:UIControlEventTouchUpInside];

   button3.backgroundColor = [UIColorblackColor];

   button3.showsTouchWhenHighlighted =YES;

   [self.viewaddSubview: button3];

   UIButton *button4 = [UIButtonbuttonWithType:UIButtonTypeCustom];

   button4.frame =CGRectMake(50,290, 200,50);

   [button4 setTitle:@"线程锁"forState:UIControlStateNormal];

   [button4 addTarget:selfaction:@selector(threadLock)forControlEvents:UIControlEventTouchUpInside];

   button4.backgroundColor = [UIColorblackColor];

   button4.showsTouchWhenHighlighted =YES;

   [self.viewaddSubview: button4];   

   UIButton *button5 = [UIButtonbuttonWithType:UIButtonTypeCustom];

   button5.frame =CGRectMake(50,350, 200,50);

   [button5 setTitle:@"NSOperationQueue"forState:UIControlStateNormal];

   [button5 addTarget:selfaction:@selector(NSOperationQueueButton)forControlEvents:UIControlEventTouchUpInside];

   button5.backgroundColor = [UIColorblackColor];

   button5.showsTouchWhenHighlighted =YES;

   [self.viewaddSubview: button5];

   UIButton *button6 = [UIButtonbuttonWithType:UIButtonTypeCustom];

   button6.frame =CGRectMake(50,410, 200,50);

   [button6 setTitle:@"GCDButton"forState:UIControlStateNormal];

   [button6 addTarget:selfaction:@selector(TouchGCDButton)forControlEvents:UIControlEventTouchUpInside];

   button6.backgroundColor = [UIColorblackColor];

   button6.showsTouchWhenHighlighted =YES;

   [self.viewaddSubview: button6];

}

//阻塞主线程 0-20亿的加法运算

- (void)blockMainThread

{

   long temp =0;

   for (long i =0; i < 2000000000; i ++) {

      temp++;

   }

   NSLog(@"%ld",temp);

}

//nsobject自带的开辟子线程的方式

- (void)touchNSobjectButton

{

   //点击按钮,不会出现按钮高亮卡停的状态将耗时操作InBackground

   [selfperformSelectorInBackground:@selector(blockMainThread)withObject:nil];

}

//NSthread

- (void)touchNSthreadButton

{

   //获取当前线程

   NSThread *thread1 = [NSThreadcurrentThread];

   NSLog(@"%@",thread1);

   //获取主线程

   NSThread *thread2 = [NSThreadmainThread];

   NSLog(@"%@",thread2);

   //判断是不是主线程

   BOOL result = [NSThreadisMainThread];

   //睡眠  (按钮高亮会卡两秒)两种方式

   //[NSThread sleepForTimeInterval:2]; //方式1

   //sleep(2); //方式2

   //开辟子线程

   NSThread *th = [[NSThreadalloc] initWithTarget:self selector:@selector(blockMainThread) object:nil];

   //加名字

   th.name =@"老子是个子线程";

   //启动线程

   //[th start];

   //第二种开子线程的方式这种方式不需要启动

   [NSThreaddetachNewThreadSelector:@selector(blockMainThread)toTarget:selfwithObject:nil];

}

#pragma mark -- 下载过程至少需要三个方法

//子线程中同步下载方式下载图片

- (void)downLoadButton

{

   //开子线程下载

   NSThread *th = [[NSThreadalloc] initWithTarget:selfselector:@selector(downLoadImage)object:nil];

   [th start];

}

//下载过程

- (void)downLoadImage

{

   NSString *str =@"http://imgsrc.baidu.com/forum/w%3D580/sign=66329da88794a4c20a23e7233ef51bac/230cb4af2edda3cccc63c48701e93901203f9248.jpg";

   NSURL *url = [NSURLURLWithString: str];

   NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];

   request.HTTPMethod =@"GET";

   NSData *data = [NSURLConnectionsendSynchronousRequest: request returningResponse:nilerror:nil];

   //回归主线程

   [selfperformSelectorOnMainThread:@selector(upDateUI:)withObject:data waitUntilDone:YES];

}

//回到主线程中 更新ui

//耗时操作在子线程中进行,更新界面的操作需要回到主线程

- (void)upDateUI:(id)object

{

   NSData *data = (NSData *)object;

}

//模拟买票 线程锁

- (void)threadLock

{

   //开辟三个子线程

   //创建锁

   NSLock *lock = [[NSLockalloc] init];

   NSThread *th1 = [[NSThreadalloc] initWithTarget:self selector:@selector(buyTicket:)object:lock];

   NSThread *th2 = [[NSThreadalloc] initWithTarget:self selector:@selector(buyTicket:)object:lock];

   NSThread *th3 = [[NSThreadalloc] initWithTarget:self selector:@selector(buyTicket:)object:lock];

   [th1 start];

   [th2 start];

   [th3 start];

}

//线程的执行是并行

- (void)buyTicket:(id)object

{

   //获取锁

   NSLock *lock = (NSLock *)object;

   while (true) {

      [lock lock];//开锁

      sleep(1);

      ticKetCount --;

      NSLog(@"%ld",ticKetCount);

      if (ticKetCount ==0) {

         break;

      }

      [lock unlock];//解锁

   }

}

//NSOperation方式开辟子线程

- (void)NSOperationQueueButton

{

   //2 第一种自己建一个类继承自NSOperation,耗时操作写在main函数里面

   /*

   MyNSOperation *op1 = [[MyNSOperation alloc] init];

   MyNSOperation *op2 = [[MyNSOperation alloc] init];

   MyNSOperation *op3 = [[MyNSOperation alloc] init];

   //创建线程池

   NSOperationQueue *queue = [[NSOperationQueue alloc] init];

   //设置最大并行个数

   [queue setMaxConcurrentOperationCount: 1]; //设置成1,实际就成了一个串行

   //将子线程添加到线程池中

   [queue addOperation:op1];

   [queue addOperation:op2];

   [queue addOperation:op3];

    */

   //第二种 NSOperation子类创建

   NSInvocationOperation *op1 = [[NSInvocationOperationalloc] initWithTarget:self selector:@selector(blockMainThread)object:nil];

   NSInvocationOperation *op2 = [[NSInvocationOperationalloc] initWithTarget:self selector:@selector(blockMainThread)object:nil];

   NSInvocationOperation *op3 = [[NSInvocationOperationalloc] initWithTarget:self selector:@selector(blockMainThread)object:nil];

   NSOperationQueue *queue = [[NSOperationQueuealloc] init];

   //设置最大并行个数

   [queue setMaxConcurrentOperationCount:1];

   [queue addOperation: op1];

   [queue addOperation: op2];

   [queue addOperation: op3];

}

//GCD

- (void)TouchGCDButton

{

   /*

   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

      //子线程(做耗时操作)

      dispatch_async(dispatch_get_main_queue(), ^{

      //主线程(更新UI

      });

   });

   */

   //分组管理所有子线程,当所有线程结束之后汇总

   /*

   dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

   dispatch_group_t group = dispatch_group_create();

   dispatch_group_async(group, queue, ^{

      sleep(1);

      NSLog(@"111");

   });

   dispatch_group_async(group, queue, ^{

      sleep(2);

      NSLog(@"222");

   });

   dispatch_group_async(group, queue, ^{

      sleep(3);

      NSLog(@"333");

   });

   dispatch_group_notify(group, queue, ^{

      NSLog(@"结束");

   });

   */

   dispatch_queue_t queue =dispatch_queue_create(nil,DISPATCH_QUEUE_CONCURRENT);

   dispatch_async(queue, ^{

      sleep(1);

      NSLog(@"111");

   });

   dispatch_async(queue, ^{

      sleep(2);

      NSLog(@"222");

   });

   dispatch_async(queue, ^{

      sleep(3);

      NSLog(@"333");      

   });

   dispatch_barrier_async(queue, ^{

      sleep(1);

      NSLog(@"障碍");

   });

   dispatch_async(queue, ^{

      sleep(1);

      NSLog(@"444");

   });

   dispatch_queue_t queue1 =dispatch_queue_create(nil,DISPATCH_QUEUE_CONCURRENT);

   dispatch_async(queue, ^{

      sleep(1);

      NSLog(@"111");

   });

   dispatch_async(queue, ^{

   });

   dispatch_async(queue, ^{

   });

   dispatch_barrier_async(queue, ^{      

   });

   dispatch_async(queue, ^{

   });

}

- (void)didReceiveMemoryWarning {

   [superdidReceiveMemoryWarning];

}

@end


//************************************************//

#import <Foundation/Foundation.h>

@interface MyNSOperation :NSOperation

@end


#import "MyNSOperation.h"

@implementation MyNSOperation

- (void)main

{

   //这里写耗时操作

   long temp =0;

   for (long i =0; i < 2000000000; i ++) {

      temp++;

   }

   NSLog(@"%ld",temp);     

}

@end



0 0
原创粉丝点击