一、pthread的使用(几乎不用)
#import "ViewController.h"
// 1.引入pthread头文件: #import <pthread.h>
#import <pthread.h>
@interface ViewController ()
@end
@implementation ViewController
void *run(void *data) {
for (int i = 0; i<10000; i++) {
// 调用NSThread的类方法currentThread返回的是
// 当前代码所在线程的相关信息(线程地址,线程数量,当前线程的名字)
NSLog(@"touchesBegan ---- %d --- %@", i, [NSThread currentThread]);
}
return 0;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 2.创建线程
pthread_t myRestict;
// 3.启动线程,调用run方法,注意⚠️run方法的返回值必须为空!
pthread_create(&myRestict, NULL, run, NULL);
}
@end
二、NSThread的使用(偶尔使用)
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)download:(NSString *)url {
NSLog(@"download something --- %@ --- %@", url, [NSThread currentThread]);
}
/**
创建线程的方式1
*/
- (void)createThread1 {
// 1.创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://a.jpg"];
// 2.启动线程(调用self的download方法)
[thread start];
// 判断thread这个线程是否是主线程
// [thread isMainThread];
// 判断当前方法是否为主线程
// [NSThread isMainThread];
// 设置线程的名字
// [thread setName:@"download_thread"];
// thread.name = @"downloadThread";
}
/**
创建线程的方式2: 创建线程后自动启动
*/
- (void)createThread2 {
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://b.png"];
}
/**
创建线程的方式3: 隐式创建线程后自动启动
*/
- (void)createThread3 {
[self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self createThread1];
// [self createThread2];
// [self createThread3];
}
@end
网友评论