NSThread

一个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];

线程的名字

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

其他创建方式

创建线程后自动启动线程

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

隐式创建并启动线程

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

上述2种创建线程方式的优缺点

优点:简单快捷

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

示例

-(void)run:(NSString *)str{
    for (NSInteger i = 0;i < 10000; i++) {
        NSLog(@"%@ -- %@",str,[NSThread currentThread]);
    }
}

-(void)createThread1{
    MyThread *thread = [[MyThread alloc] initWithTarget:self selector:@selector(run:) object:@"momo"];
    thread.name = @"fofo";
    [thread start];
}

-(void)createThread2{
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"toto"];
}

-(void)createThread3{
    [self performSelectorInBackground:@selector(run:) withObject:@"coco"];
}

控制线程状态

启动线程

- (void)start; 
// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态

阻塞(暂停)线程

+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 进入阻塞状态

强制停止线程

+ (void)exit;
// 进入死亡状态

注意:一旦线程停止(死亡)了,就不能再次开启任务

什么叫做线程间通信

在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信

线程间通信的体现

1个线程传递数据给另1个线程

在1个线程中执行完特定任务后,转到另1个线程继续执行任务

线程间通信常用方法

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;

results matching ""

    No results matching ""