0708線程
多線程
pthread (了解庐杨,程序猿幾乎不用)
// 創(chuàng)建線程
pthread_t pthread;
/*
// 執(zhí)行線程參數(shù)
// thread_t *restrict:線程的地址
// const pthread_attr_t *restrict
// void *(*)(void *) 指向函數(shù)的指針
// void *restrict
pthread_create(pthread_t *restrict, const pthread_attr_t *restrict, void *(*)(void *), void *restrict);
*/
// 一般會(huì)這樣寫
// run:指向函數(shù)的指針谴蔑,將需要執(zhí)行的代碼放入指向函數(shù)的指針中俭嘁。
pthread_create(&thread, NULL, run, NULL);
-
例圖
NSThread (掌握)
- NSThread 創(chuàng)建方式一
// 創(chuàng)建線程
NSThread *thread = [[NSThread allow] initWithTarget:self selector:@selector(run:) object:@"jack"];
// 線程名稱
thread.name = @"myThread";
// 啟動(dòng)線程
[thread strat];
-
例圖
NSThread 創(chuàng)建方式二
// 直接創(chuàng)建線程,調(diào)用run方法篮奄,參數(shù)為rose
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"rose"];
-
例圖
創(chuàng)建方式三
// 直接創(chuàng)建線程霹肝,然后運(yùn)行叉袍,調(diào)用run方法,參數(shù)為rose
[NSThread performSelectorInBackground:@selector(run:) withObject:@"jack"];
-
例圖
線程的狀態(tài)
使線程延時(shí)然后運(yùn)行之后的程序
// 線程延時(shí)兩秒運(yùn)行之后程序
1.[NSThread sleepForTimeInterval:2];
2.[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
// 延時(shí)到遙遠(yuǎn)的未來
1.[NSThread sleepUntilDate:[NSDate distantFuture]];
// 直接退出線程
[NSThread exit];
// 獲得當(dāng)前線程
NSThread *current = [NSThread currentThread];
// 主線程相關(guān)用法
+ (NSThread *)mainThread; // 獲得主線程
- (BOOL)isMainThread; // 是否為主線程
+ (BOOL)isMainThread; // 是否為主線程
// 獲取1970年到現(xiàn)在走過的時(shí)間
CFTimeInterval end = CFAbsoluteTimeGetCurrent();
// 獲取0時(shí)區(qū)當(dāng)前的時(shí)間
NSDate *begin = [NSDate date];
-
例圖
線程的安全
互斥鎖使用格式
@synchronized(鎖對(duì)象) { // 需要鎖定的代碼 }
注意:鎖定1份代碼只用1把鎖瘪阁,用多把鎖是無效的互斥鎖的使用前提:多條線程搶奪同一塊資源
線程同步
線程同步的意思是:多條線程在同一條線上執(zhí)行(按順序地執(zhí)行任務(wù))
互斥鎖撒遣,就是使用了線程同步技術(shù)當(dāng)線程需要訪問同一區(qū)域的變量時(shí)就要考慮線程數(shù)據(jù)的安全性邮偎,使用互斥鎖來保證數(shù)據(jù)的安全性
這里詳細(xì)說明太羅嗦,直接上代碼
加載網(wǎng)絡(luò)圖片
- 加載方式二
// 添加圖片網(wǎng)絡(luò)路徑
NSURL *url = [NSURL URLWithString:@"http://bgimg1.meimei22.com/list/2015-4-23/1/013.jpg"];
// 將文件路徑下得圖片包裝成對(duì)象
NSData *date = [NSData dataWithContentsOfURL:url];
// 將對(duì)象轉(zhuǎn)成imget圖片
UIImage *image = [UIImaeg imageVithData:date];
// 再將圖片給需要顯示的iamgeView
imageView.image = imaeg;
-
例圖
加載方式二
// 加載圖片路徑
NSURL *url = [NSURL URLWithString:@"http://bgimg1.meimei22.com/list/2015-4-23/1/013.jpg"];
// 將圖片轉(zhuǎn)成對(duì)象
NSData *date = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:date];
// 進(jìn)入主線程加載圖片
[self.image performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
-
例圖