pThread 使用方法ide
#import "ViewController.h" #import <pthread.h> //pThread须要导入 @interface ViewController ()<UIScrollViewDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *but1 = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 30)]; [but1 setTitle:@"pThread" forState:UIControlStateNormal]; [but1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [but1 addTarget:self action:@selector(pThreadClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:but1]; } #pragma mark pThread是基于C语言的线程 OC里面不经常使用 - (void)pThreadClick{ NSLog(@"这是主线程"); pthread_t pthread; //建立一个线程 pthread_create(&pthread, NULL, run, NULL); //run 是要执行的方法按照C语言来写 } void *run(void *dadta){ NSLog(@"这是子线程"); for (int i = 0; i< 10; i++) { NSLog(@"%d",i); sleep(1);//线程休眠 } return NULL; }
NSThread 的使用线程
#import "ViewController.h" @interface ViewController ()<UIScrollViewDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *but1 = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 30)]; [but1 setTitle:@"NSThread" forState:UIControlStateNormal]; [but1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [but1 addTarget:self action:@selector(NSThreadClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:but1]; } #pragma mark NSThread 彻底面向对象 - (void)NSThreadClick{ NSLog(@"这是主线程"); //第一种方法 NSThread *thread1 = [[NSThread alloc]initWithBlock:^{ NSLog(@"这是子线程"); for (int i = 0; i< 10; i++) { NSLog(@"%d",i); sleep(1);//线程休眠 } }]; [thread1 setName:@"thread1"]; [thread1 setThreadPriority:.7];//设置线程优先级 0-1 [thread1 start]; NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil]; [thread2 setThreadPriority:.4];//设置线程优先级 0-1 [thread2 setName:@"thread2"];//设置线程名字 [thread2 start]; //第二种方法 经过detachNewThreadSelector 静态方法 // [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil]; //第三种方法 经过Object下的 performSelectorInBackground 方法建立 // [self performSelectorInBackground:@selector(run) withObject:nil]; } - (void)run{ NSLog(@"这是子线程:%@",[NSThread currentThread].name); for (int i = 0; i< 10; i++) { NSLog(@"%d",i); sleep(1);//线程休眠 } }