IOS_NSThread简单使用

//
//  PJViewController.m
//  多线程
//
//  Created by pj on 14-8-2.
//  Copyright (c) 2014年 pj. All rights reserved.
//

#import "PJViewController.h"

@interface PJViewController ()

@end

@implementation PJViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)click:(id)sender {
//    [NSThread sleepForTimeInterval:3.0f]; // 暂停3秒
//    [NSThread exit]; // 终止线程
    [self createThread4 ];
}

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

- (void)createThread3
{
    // 创建后马上执行
    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"hehe"];
}
- (void)createThread2
{
    // 创建后马上执行
    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
}

- (void)creatThread1
{

    // 1.实例化线程对象
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    thread.name = @"myThread";
    [thread start];
    
}

- (void)run:(id)obj
{
    // 加锁
    @synchronized(self)
    {
    // <NSThread: 0x8c19380>{name = (null), num = 1} 1表示主线程
    NSLog(@"%@",[NSThread currentThread]);
    NSLog(@"%@",[NSThread mainThread]);
    NSLog(@"%@",obj);
    for (int i = 11111011; i < 1; i++) {
        NSLog(@"%d",i);
    }
    // 我们在子线程里面不能直接调用更新ui的方法,那我们该怎么做呢??C#有个invoke,那么OC里呢?
    // 你木有看错,就是这么简单,最后的一个参数表示是否等待这个函数调用完毕
    [self performSelectorOnMainThread:@selector(update) withObject:@"zhangsan" waitUntilDone:NO];
    }
}

@end

 

posted @ 2014-08-02 02:27  宝贝,我永远都在  阅读(131)  评论(0)    收藏  举报