多线程NSThread的简单创建和使用——创建线程的几种方式

来源:互联网 发布:淘宝泰国代购推荐 编辑:程序博客网 时间:2024/06/05 17:31
 一个NSThread对象就代表一条线程。
创建、启动线程

NSThread *thread = [[NSThread alloc] initWithTarget:self selector: @selector(run) object: nil];
[thread start];
// 线程一启动,就会在线程thread中执行self的run方法


主线程相关的方法
+(NSThread *)mainThread; // 获得主线程
-(BOOL) isMainThread; // 是否为主线程
+(BOOL) isMainThread; // 是否为主线程


获取当前线程

NSThread *current = [NSThread currentThread];

线程的调度优先级

+(double) threadPriority;
+(BOOL)setThreadPriority:(double) p;
-(double) threadPriority;
-(BOOL)setThreadPriority:(double) p;
调度优先级的取值范围是0.0~1.0 默认是0.5,值越大,优先级越高。 自己开发时一般不建议修改优先级。


线程的名字

-(void)setName:(NSString *)n;

-(NSString *)name;


// 创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject: nil];
// 隐式创建并启动线程
[self performSelectorInBackground:@selector( run) withObject:nil];
上述2种创建线程方式的优缺点
优点:简单快捷

缺点:无法对线程进行更详细的设置。

新建工程,代码如下:

////  ViewController.m//  NSThread的简单使用与了解////  Created by apple on 15/10/4.//  Copyright (c) 2015年 LiuXun. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    }- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    }-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    //    [self test1];    //    [self test2];    //    [self test3];    [self test4];}#pragma mark 创建线程的方式一-(void)test1{    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"hello"];    [thread start];   // 注意以alloc  initWithTarget这种方式创建的线程必须调用一下start才真正执行指定的方法内容}#pragma mark 创建线程的方式二-(void)test2{    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"detach"];    // 注意以此种方式创建的线程,创建完成直接执行,而不用再调用start方法}#pragma mark 创建线程的方式三-(void)test3{    // 此种创建方法为隐士创建线程    [self performSelectorInBackground:@selector(run:) withObject:@"performBack"];}#pragma mark 创建线程的方式四-(void) test4{    NSThread *threadA = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"A"];    threadA.name = @"threadA";    threadA.threadPriority = 0.1;    [threadA start];        NSThread *threadB = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"B"];    threadB.name = @"thread B";    threadB.threadPriority = 1.0;    [threadB start];    }// 耗时操作-(void)run:(id) obj{    for (int i=0 ; i<10 ; i++)    {        NSLog(@"%@- %@", [NSThread currentThread], obj);    }// 注意:在哪个方法内执行的currentThread方法,获取的就是调度所在方法的线程}@end
执行test1方法如下:


执行test2方法如下:


执行test3方法如下:


执行test4方法只执行线程A如下:


执行test4方法设置优先级后同时执行线程A和线程B如下:

发现两个线程同时执行时,哪个线程的优先级越高,获得时间片的几率就越大,就越快执行完毕任务。

线程优先级是一个浮点数,0.0~1.0 默认是0.5,开发的时候一般不去修改优先级的值。优先级必须调用很多次的时候,优点才会体现出来。


0 0