<span style="font-size:14px;color:#cc0000;"><strong>- (void)viewDidLoad {
// 创建方式一
NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];
// 创建方式二 直接开辟并且执行
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
// 创建方式三
[self performSelectorInBackground:@selector(run) withObject:nil];
// 创建方式四
NSOperationQueue* operation = [[NSOperationQueue alloc] init];
operation.maxConcurrentOperationCount = 1;//指定池子的并发数
// 任务A
NSInvocationOperation* invation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
// 任务B
NSInvocationOperation* invation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
//设置线程优先级
invation.queuePriority = NSOperationQueuePriorityHigh;
//将任务添加到池子里面,可以给池子添加多个任务,并且指定它的并发数
[operation addOperation:invation];
[operation addOperation:invation1];
// 第五种方式
NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:^{
//这个block语句块在子线程中执行
NSLog(@"START");
}];
// 第六种方式
// 调用主线程,用于子线程和主线程的交互,最后面的那个done参数如果为yes就是等这个方法执行完了在执行
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
// 第六种方式
//--------------GCD----------支持多核,高效率的多线程技术
dispatch_queue_t queue = dispatch_queue_create("name", NULL);
dispatch_async(queue, ^{
NSLog(@"创建一个异步子线程");
// 执行点什么
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"回到主线程 %@",[NSThread currentThread]);
});
});
[super viewDidLoad];
}
- (void)run
{
NSLog(@"多线程运行!");
}</strong></span>