iOS 创建线程的多种方法

                   我在AppDelegate.m里写的代码。连续介绍几个创建线程的方法。

                  

#import "AppDelegate.h"

@interface AppDelegate ()

 

@end

 

@implementation AppDelegate

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    self.window.rootViewController = [[UIViewController alloc]init];

    

//  第一种

    //NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(mutableThread:) object:nil];

    //[thread start];

 

 

    //第二种方法

    //[NSThread detachNewThreadSelector:@selector(mutableThread:) toTarget:self withObject:nil];

 

    //3方法

    //[self performSelectorInBackground:@selector(mutableThread:) withObject:nil];

 

    //4种方法

   // NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];

    //[operationQueue addOperationWithBlock:^{

//for (int i = 0; i<100; i++) {

     //       NSLog(@"主线程",i);

    //    }

    //}];

 

    //5中方法

    //创建一个线程队列

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

    //设置线程执行的并发数//设置并发数为1后,那线程2最后执行

    operationQueue.maxConcurrentOperationCount = 1;

    //创建一个线程操作对象

    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread:) object:nil];

    //创建一个线程操作对象

    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread2:) object:nil];

    //设置线程的优先级

    operation2.queuePriority = NSOperationQueuePriorityHigh;

    //将线程添加到线程队列中

    [operationQueue addOperation:operation];

    [operationQueue addOperation:operation2];

        return YES;

}

- (void)mutableThread:(NSString *)t

{

    for (int i=0; i<100; i++) {

        NSLog(@"--%d多线程",i);

    }

    //跳到主线程执行

    [self performSelectorOnMainThread:@selector(mainThread) withObject:nil waitUntilDone:YES];

}

- (void)mutableThread2:(NSString *)t

{

    for (int i=0; i<100; i++) {

        NSLog(@"---%d多线程2",i);

    }

}

- (void)mainThread

{

    BOOL isMain = [NSThread isMainThread];

    if (isMain) {

        NSLog(@"1111111111111111111mainThread");

    }

}

@end

欢迎指正错误,相互学习,欢迎加入IT技术学习交流群:554587323

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值