一、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++) {
// 調(diào)用NSThread的類方法currentThread返回的是
// 當(dāng)前代碼所在線程的相關(guān)信息(線程地址,線程數(shù)量,當(dāng)前線程的名字)
NSLog(@"touchesBegan ---- %d --- %@", i, [NSThread currentThread]);
}
return 0;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 2.創(chuàng)建線程
pthread_t myRestict;
// 3.啟動(dòng)線程,調(diào)用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]);
}
/**
創(chuàng)建線程的方式1
*/
- (void)createThread1 {
// 1.創(chuàng)建線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://a.jpg"];
// 2.啟動(dòng)線程(調(diào)用self的download方法)
[thread start];
// 判斷thread這個(gè)線程是否是主線程
// [thread isMainThread];
// 判斷當(dāng)前方法是否為主線程
// [NSThread isMainThread];
// 設(shè)置線程的名字
// [thread setName:@"download_thread"];
// thread.name = @"downloadThread";
}
/**
創(chuàng)建線程的方式2: 創(chuàng)建線程后自動(dòng)啟動(dòng)
*/
- (void)createThread2 {
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://b.png"];
}
/**
創(chuàng)建線程的方式3: 隱式創(chuàng)建線程后自動(dòng)啟動(dòng)
*/
- (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
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。