作為一名iOS開發(fā)人員,無論你是新手還是大師級別的人,相信對多線程都會陌生,下文是武林技術(shù)頻道小編為你分析iOS多線程開發(fā),一起進入下文了解一下吧!
為你分析iOS多線程開發(fā)
一、簡單介紹
線程的創(chuàng)建:
?
?
?
?
說明:創(chuàng)建線程有多種方式,這里不做過多的介紹。

線程的開啟:
?
?
?
?

線程的運行和阻塞:
(1)設(shè)置線程阻塞1,阻塞2秒
[NSThread sleepForTimeInterval:2.0];
(2)第二種設(shè)置線程阻塞2,以當(dāng)前時間為基準(zhǔn)阻塞4秒
?
?

線程處理阻塞狀態(tài)時在內(nèi)存中的表現(xiàn)情況:(線程被移出可調(diào)度線程池,此時不可調(diào)度)

線程的死亡:
當(dāng)線程的任務(wù)結(jié)束,發(fā)生異常,或者是強制退出這三種情況會導(dǎo)致線程的死亡。

線程死亡后,線程對象從內(nèi)存中移除。

二、代碼示例
代碼示例1:
//// YYViewController.m// -NSThread-線程的狀態(tài)//// Created by apple on --.// Copyright (c) 年 itcase. All rights reserved.//#import "YYViewController.h"@interface YYViewController ()@property(nonatomic,strong)NSThread *thread;@end@implementation YYViewController- (void)viewDidLoad{[super viewDidLoad];//創(chuàng)建線程self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];//設(shè)置線程的名稱[self.thread setName:@"線程A"];}//當(dāng)手指按下的時候,開啟線程-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{//開啟線程[self.thread start];}-(void)test{//獲取線程NSThread *current=[NSThread currentThread];NSLog(@"test---打印線程---%@",self.thread.name);NSLog(@"test---線程開始---%@",current.name);//設(shè)置線程阻塞,阻塞秒NSLog(@"接下來,線程阻塞秒");[NSThread sleepForTimeInterval:.];//第二種設(shè)置線程阻塞,以當(dāng)前時間為基準(zhǔn)阻塞秒NSLog(@"接下來,線程阻塞秒");NSDate *date=[NSDate dateWithTimeIntervalSinceNow:.];[NSThread sleepUntilDate:date];for (int i=; i打印查看:

代碼示例2(退出線程):
//// YYViewController.m// -NSThread-線程的狀態(tài)//// Created by apple on --.// Copyright (c) 年 itcase. All rights reserved.//#import "YYViewController.h"@interface YYViewController ()@property(nonatomic,strong)NSThread *thread;@end@implementation YYViewController- (void)viewDidLoad{[super viewDidLoad];//創(chuàng)建線程self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil];//設(shè)置線程的名稱[self.thread setName:@"線程A"];}//當(dāng)手指按下的時候,開啟線程-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{//開啟線程[self.thread start];}-(void)test{//獲取線程NSThread *current=[NSThread currentThread];NSLog(@"test---打印線程---%@",self.thread.name);NSLog(@"test---線程開始---%@",current.name);//設(shè)置線程阻塞,阻塞秒NSLog(@"接下來,線程阻塞秒");[NSThread sleepForTimeInterval:.];//第二種設(shè)置線程阻塞,以當(dāng)前時間為基準(zhǔn)阻塞秒NSLog(@"接下來,線程阻塞秒");NSDate *date=[NSDate dateWithTimeIntervalSinceNow:.];[NSThread sleepUntilDate:date];for (int i=; i打印示例:

注意:人死不能復(fù)生,線程死了也不能復(fù)生(重新開啟),如果在線程死亡之后,再次點擊屏幕嘗試重新開啟線程,則程序會掛。

以上內(nèi)容是武林技術(shù)頻道小編給大家介紹的為你分析iOS多線程開發(fā) ,希望大家喜歡。
新聞熱點
疑難解答
圖片精選