多线程编程

程序:可执行文件

    进程:一个正在运行的可执行文件,每个进程都有独立的虚拟内存空间和系统资源,包括端口权限等,并且至少包含一个主线程和任意数量的辅助线程。另外,当一个进程的主线程退出时,这个进程就结束了。

    线程:一个独立代码执行路径(线程是代码执行的最小分支),有线程做资源的分配和调度。


//  AppDelegate.m

#import "AppDelegate.h"
#import "RootViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)dealloc
{
    self.window = nil;
    [super dealloc];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    RootViewController *rootVC = [[RootViewController alloc]init];
    self.window.rootViewController = rootVC;
    [rootVC release];
    
    return YES;
}

@end



//  RootViewController.m

#import "RootViewController.h"

@interface RootViewController () {
    UIImageView *imageView;
}

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor yellowColor];
    imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"taiji"]];
    imageView.center = CGPointMake(375 / 2.0, 120);
    imageView.layer.cornerRadius = 101;//将图片的边框设置成圆角
    imageView.layer.masksToBounds = YES;//隐藏边界
    [self.view addSubview:imageView];
    [imageView release];
    
    // NSTimer其实是将一个监听加入到系统的RunLoop中去,当系统runloop到如何timer条件的循环时,会调用timer一次,当timer执行完,也就是回调函数执行之后,timer会再一次的将自己加入到runloop中去继续监听。
    [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(taiji) userInfo:nil repeats:YES];
    //[self server];//调用server方法,会出现假死想象。
    
    //iOS创建线程的方式:
/*
    //a、NSObject
    //调用此方法,执行的操作在后台线程中执行。
    //[self performSelectorInBackground:@selector(serverPro:) withObject:@"秋波"];
*/
    
/*
    //b、NSThread
    //NSThread, 线程类,继承于NSObject
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(serverPro:) object:@1];
     //线程命名
     thread.name = @"翠花";
     NSLog(@"%@", thread);
     [thread start];
     [thread release];
    
    //获取主线程
    NSThread *mainThread = [NSThread mainThread];
    NSLog(@"mainThread:%@", mainThread);
    
    //线程休眠
    //[NSThread sleepForTimeInterval:5];
    
    //主线程和子线程的区别:
    //1、能够分配资源的最大容量不同,主线程10MB,子线程5MB。
    //2、子线程不会释放autorelease的对象,需要手动添加自动释放池。
    //3、更新UI的操作必须在主线程中执行。
*/
    
/*
     //c、NSOperationQueue
     //NSOperationQueue:操作队列(任务队列),继承于NSOBject,操作队列绑定的有一个线程。
     
     //队列和栈的结构:
     //栈:先进后出
     //队列:先进先出
     
     //任务(操作):一段代码
     
     //NSOperation:任务(操作)类,继承于NSobject,是抽象基类:
     //子类:NSInvocationOperation,NSBlockOperation
     
     //串行,并发,主要区别在于:同时执行任务的数量
     //串行:一次只能执行一个任务,并且必须等上一个任务执行完,才能执行下一个任务。
     //并发:允许多个任务同时执行。
     
     //创建任务
     //注:任务只能够执行一次,已经添加到队列中,就不能再添加。
    NSInvocationOperation *invocation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(serverPro:) object:nil];
    //主线程执行任务
    [invocation start];
    
    NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
        for (NSInteger i = 1; i <= 100; i++) {
            NSLog(@"%ld", i);
        }
    }];
    
    //任务依赖关系
    [invocation addDependency:block];
    
    //创建操作队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    //最大并发数,默认为-1,代表无限个
    queue.maxConcurrentOperationCount = -1;
    //把任务添加到队列中,一旦添加到队列,任务就会在队列绑定的线程中执行
    //方法1、
    //[queue addOperation:invocation];//任务只能够执行一次,已经添加到队列中,就不能再添加
    [queue addOperation:block];
    //方法2、
    //[queue addOperations:@[invocation, block] waitUntilFinished:NO];
    
    [queue addOperationWithBlock:^{
        NSLog(@"Hello, world!");
    }];
    
    //取消操作:
    //一旦任务添加到操作队列中,不能移除,只能取消,并且只能取消没有执行的操作。
    //[block cancel];//取消单个任务
    
    //[self performSelector:<#(SEL)#> withObject:<#(id)#> afterDelay:<#(NSTimeInterval)#> inModes:<#(NSArray *)#>];
    
    //[queue cancelAllOperations];//取消所有任务
    
    [invocation release];
    [queue release];
*/
    
    //d、GCD
    //GCD:Grand Central Dispatch,大中央调度,基于CPU的多核技术实现,使用C语言的语法,执行效率更高,NSOperationQueue基于GCD实现。
    //三种队列
    //主队列:绑定主线程,串行队列。
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    NSLog(@"%@", mainQueue);
    
    //全局队列:绑定子线程,并发执行。
    //参数1:队列优先级
    //DISPATCH_QUEUE_PRIORITY_HIGH            高
    //DISPATCH_QUEUE_PRIORITY_DEFAULT         默认
    //DISPATCH_QUEUE_PRIORITY_LOW             低
    //DISPATCH_QUEUE_PRIORITY_BACKGROUND      后台
    //参数2:预留参数,为未来做准备。
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    NSLog(@"%@", globalQueue);
    
    //自定义队列,绑定子线程,串行或并发
    //参数1:队列标示符,域名
    //参数2:并发DISPATCH_QUEUE_CONCURRENT或串行DISPATCH_QUEUE_SERIAL
    dispatch_queue_t customQueue = dispatch_queue_create("com.lanou3g.kris", DISPATCH_QUEUE_SERIAL);
    NSLog(@"%@", customQueue);
    
    //把操作放到队列,有两种方式:
    //同步执行
    //    dispatch_sync(mainQueue, ^{
    //        //写操作
    //        [self serverPro:nil];
    //    });
    
    //异步执行
    //    dispatch_async(globalQueue, ^{
    //        [self serverPro:nil];
    //    });
    
    //多少秒后执行某个操作
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"睡觉");
    });
    
    //程序运行期间,只执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"Hello, world");
    }); 

}

//设置图片旋转
-(void)taiji {
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        imageView.transform = CGAffineTransformRotate(imageView.transform, M_PI_4);
    } completion:^(BOOL finished) {
        
    }];
}

-(void)server {
    //当主线程执行复杂操作时,就会阻塞主线程造成程序假死状态,此时需要为复杂的操作开辟线程来执行。
    for (NSInteger i = 0; i <= 10000; i++) {
        NSLog(@"%ld", i);
    }
}

-(void)serverPro:(id)string {
    @autoreleasepool {
        NSLog(@"%@", string);
        
        //获取当前代码执行的线程
        NSThread *currentThread = [NSThread currentThread];
        NSLog(@"%@", currentThread);
        
        for (NSInteger i = 0; i <= 10; i++) {
            [NSThread sleepForTimeInterval:1];
            NSString *string = [NSString stringWithFormat:@"客户%ld, 你好,欢迎光临。", i];
            NSLog(@"%@", string);
        }
        //跳回到主线程,执行某个方法
        [self performSelectorOnMainThread:@selector(refreshUI) withObject:nil waitUntilDone:YES];
    }
}

-(void)refreshUI {
    self.view.backgroundColor = [UIColor greenColor];
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值