多线程NSThread

//

//  ViewController.m

//  多线程

//

//  Created by 谢泽锋 on 16/4/24.

//  Copyright © 2016年 xiezefeng. All rights reserved.

//

 

#import "ViewController.h"

#import <pthread.h>

#import "ZFthread.h"

@interface ViewController ()

 

@end

 

@implementation ViewController

void * run(void *param){

    

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

        NSLog(@"run%@",[NSThread currentThread]);

    }

 

    

    

    return NULL;

}

- (IBAction)action:(id)sender {

    NSLog(@"是否是主线程===%d",  [NSThread isMainThread]);

 

//    pthread_t thread;

//    pthread_create(&thread, NULL, run, NULL);

    

//    ZFthread * thread=[[ZFthread alloc]initWithTarget:self selector:@selector(play:) object:@"jack"];

//    [thread start];//开启线程

//    thread.name=@"zefeng";

    

//    1

    NSThread * thread=[[NSThread alloc]initWithTarget:self selector:@selector(play:) object:@"jack"];

//    [thread isMainThread];//是否是主线程

//    [NSThread isMainThread];//是否是主线程

//    NSLog(@"是否是主线程===%d",  [thread isMainThread]);

    [thread start];//开启线程

    thread.name=@"zefeng";

    

    // 2 直接从主线程中剥离出来的子线程 当不能设名字

//    [NSThread detachNewThreadSelector:@selector(play:) toTarget:self withObject:@"fengzi"];

//   3 无法对线程跟详细的设置

//    [self performSelectorInBackground:@selector(play:) withObject:@"xiexiaofeng"];

//    4 done 是否掐住等到任务完成为止

//    [self performSelectorOnMainThread:@selector(play:) withObject:@"" waitUntilDone:NO];

    

}

-(void)play:(NSString*)str

{

    

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

//        [NSThread sleepForTimeInterval:3];//让线程阻塞2秒

//        [NSThread sleepUntilDate:[NSDate distantFuture]];//睡眠到某个时期

        [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];

        if (i==2) {

//            exit(0);

            [NSThread exit];//直接退出线程

            

        }

        NSLog(@"str==%@ currentThread==%@",str,[NSThread currentThread]);

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

- (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.

}

 

@end

 

posted @ 2016-04-24 16:43  谢小锋  阅读(100)  评论(0)    收藏  举报