標籤:
2.pthread
(1)pthread的基本使用(需要包含標頭檔#import
/* 第一個參數:線程對象 第二個參數:線程屬性 第三個參數:void *(*)(void *) 指向函數的指標 第四個參數:傳遞給該函數的參數 */int pthread_create(pthread_t * __restrict, const pthread_attr_t * __restrict, void *(*)(void *), void * __restrict);
使用舉例:
// 建立線程 pthread_t thread; pthread_create(&thread, NULL, run, NULL);
void *run(void *param){ for (NSInteger i =0 ; i<10000; i++) { NSLog(@"%zd--%@",i,[NSThread currentThread]); } return NULL;}
3.NSThread
(1)NSThread的基本使用
//第一種建立線程的方式:alloc init.//特點:需要手動開啟線程,可以拿到線程對象進行詳細設定 //建立線程 /* 第一個參數:目標對象 第二個參數:選取器,線程啟動要調用哪個方法 第三個參數:前面方法要接收的參數(最多隻能接收一個參數,沒有則傳nil) */ NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"wendingding"]; //啟動線程 [thread start];
//第二種建立線程的方式:分離出一條子線程//特點:自動啟動線程,無法對線程進行更詳細的設定 /* 第一個參數:線程啟動調用的方法 第二個參數:目標對象 第三個參數:傳遞給調用方法的參數 */ [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"我是分離出來的子線程"];
//第三種建立線程的方式:後台線程//特點:自動啟動線程,無法進行更詳細設定[self performSelectorInBackground:@selector(run:) withObject:@"我是後台線程"];
(2)設定線程的屬性
//設定線程的屬性 //設定線程的名稱 thread.name = @"線程A"; //設定線程的優先順序,注意線程優先順序的取值範圍為0.0~1.0之間,1.0表示線程的優先順序最高,如果不設定該值,那麼理想狀態下預設為0.5 thread.threadPriority = 1.0;
(3)線程的狀態(瞭解)
//線程的各種狀態:建立-就緒-運行-阻塞-死亡//常用的控制線程狀態的方法[NSThread exit];//退出當前線程[NSThread sleepForTimeInterval:2.0];//阻塞線程[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];//阻塞線程//注意:線程死了不能複生
(4)線程間通訊
-(void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{// [self download2]; //開啟一條子線程來下載圖片 [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];}-(void)downloadImage{ //1.確定要下載網狀圖片的url地址,一個url唯一對應著網路上的一個資源 NSURL *url = [NSURL URLWithString:@"http://p6.qhimg.com/t01d2954e2799c461ab.jpg"]; //2.根據url地址下載圖片資料到本地(位元據 NSData *data = [NSData dataWithContentsOfURL:url]; //3.把下載到本地的位元據轉換成圖片 UIImage *image = [UIImage imageWithData:data]; //4.回到主線程重新整理UI //4.1 第一種方式// [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES]; //4.2 第二種方式// [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES]; //4.3 第三種方式 [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];}
(5)安全執行緒
01 前提:多個線程訪問同一塊資源會發生資料安全問題 02 解決方案:加互斥鎖 03 相關代碼:@synchronized(self){} 04 專業術語-線程同步 05 原子和非原子屬性(是否對setter方法加鎖)
(6)如何計算程式碼片段的執行時間
//第一種方法 NSDate *start = [NSDate date]; //2.根據url地址下載圖片資料到本地(位元據) NSData *data = [NSData dataWithContentsOfURL:url]; NSDate *end = [NSDate date]; NSLog(@"第二步操作花費的時間為%f",[end timeIntervalSinceDate:start]);//第二種方法 CFTimeInterval start = CFAbsoluteTimeGetCurrent(); NSData *data = [NSData dataWithContentsOfURL:url]; CFTimeInterval end = CFAbsoluteTimeGetCurrent(); NSLog(@"第二步操作花費的時間為%f",end - start);
iOS多線程(2)基本使用