iOS 创建线程的多种方法

来源:互联网 发布:fc2无域名版 编辑:程序博客网 时间:2024/05/29 07:36

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

                  

#import "AppDelegate.h"

@interface AppDelegate ()


@end


@implementation AppDelegate


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

    self.window = [[UIWindowalloc] initWithFrame:[UIScreenmainScreen].bounds];

    self.window.backgroundColor = [UIColorwhiteColor];

    [self.windowmakeKeyAndVisible];

    self.window.rootViewController = [[UIViewControlleralloc]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 = [[NSOperationQueuealloc] init];

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

    operationQueue.maxConcurrentOperationCount =1;

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

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

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

    NSInvocationOperation *operation2 = [[NSInvocationOperationalloc] initWithTarget:selfselector:@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);

    }

    //跳到主线程执行

    [selfperformSelectorOnMainThread:@selector(mainThread)withObject:nilwaitUntilDone:YES];

}

- (void)mutableThread2:(NSString *)t

{

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

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

    }

}

- (void)mainThread

{

    BOOL isMain = [NSThreadisMainThread];

    if (isMain) {

        NSLog(@"1111111111111111111mainThread");

    }

}

@end


0 0