NSThread

来源:互联网 发布:centos配置双网卡双ip 编辑:程序博客网 时间:2024/06/05 03:28


#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    

}


- (void)createThread3

{

    // NSObjcet 一个分类方法

    //在后台执行的方法:隐式的开启的线程的方式

    // 不需要手动启动

    // 用的比较多.

    [selfperformSelectorInBackground:@selector(longTimeOperation:)withObject:@"隐式开启线程"];


}


- (void)createThread2

{

    //从当前线程分离出新的线程

    //仅仅是简单地开启一条线程执行任务.

    //通过这种方式开启的线程,不能设置属性

    //不需要手动启动线程

    [NSThreaddetachNewThreadSelector:@selector(longTimeOperation:)toTarget:selfwithObject:@"分离线程"];

}


- (void)createThread1

{

    // NSThread 非常古老. 通过NSThread 可以得到一个线程对象.

    //可以设置线程的一些属性.

    

    //创建一个线程对象

   NSThread *thread = [[NSThreadalloc] initWithTarget:selfselector:@selector(longTimeOperation:)object:@"Hello NSThread"];

    

    // 设置线程在内存中的大小 //1M

    thread.stackSize =1024 *1024;

    

    // 设置线程的优先级 : 0~1.0 数字越大,优先级越高,默认是 0.5

    thread.threadPriority =0.8;

    //一般不要设置线程的优先级,有可能造成优先级反转的问题.

    //优先级反转: 低优先级的任务优先执行,造成高优先级的任务无法执行.

    // 线程状态.

    

    // 设置线程的名字

    //大型商业项目,出现问题之后,可以通过线程名称快速定位Bug.

    thread.name =@"com.itcast";

    

    //启动线程:告诉CPU准备好了.您老可以执行了.

    [threadstart];

    

    // 方法:

    //调试程序(获得当前线程)

    [NSThreadcurrentThread];

    

    // 获得主线程

    //为什么要获得主线程?

    //目的:快速/方便/随时回到主线程

    [NSThreadmainThread];

    

    // 让线程睡眠3秒钟

    [NSThreadsleepForTimeInterval:3];

    

    //不要纠结用哪一个方法,都一样.

    NSDate *date = [NSDatedateWithTimeIntervalSinceNow:3];

    [NSThreadsleepUntilDate:date];

    

    // 强制退出线程

    //对于已经强制退出(销毁)的线程,如果再次执行,会使程序奔溃.

    [NSThreadexit];

}


// 在子线程中执行的耗时方法

- (void)longTimeOperation:(NSString *)name

{

   //  NSLog(@"睡三秒");

    

    // 让线程睡眠3秒钟

    

    // 阻塞线程:调用sleep 就会阻塞线程.

    // 阻塞线程:使线程不被CPU执行

    //[NSThread sleepForTimeInterval:3];

    

    NSLog(@"下载图片---->%@ %@",name,[NSThreadcurrentThread]);

}


0 0
原创粉丝点击