NSThread
- 一個NSThread對象就代表一條線程
- NSThread會在執(zhí)行完任務函數是被自動收回
- 一些常用的函數
//創(chuàng)建線程
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector() object:nil];
//object存的是參數
//修改參數名
thread.name = @"我的多線程";
//獲取主線程
NSThread *thread = [NSThread mainThread];
//創(chuàng)建線程并自動啟動
[NSThread detachNewThreadSelector:@selector() toTarget:self withObject:nil];
//隱士創(chuàng)建
[self performSelectorInBackground:@selector() withObject:nil];
//獲取當前線程
[NSThread currentThread]
//啟動線程
- (void)start;
//阻塞(暫停)線程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 進入阻塞狀態(tài)
//停止當前正在運行的進程
+ (void)exit;
// 進入死亡狀態(tài)君躺,一旦死亡則不能重啟
資源共享
- 1塊資源可能會被多個線程共享峭判,也就是多個線程可能會訪問同一塊資源
- 當多個線程訪問同一塊資源時,很容易引發(fā)數據錯亂和數據安全問題
解決辦法互斥鎖
-
互斥鎖使用格式
- @synchronized(鎖對象) { // 需要鎖定的代碼 }
- 只用一把鎖,多鎖是無效的
-
互斥鎖的優(yōu)缺點
- 優(yōu)點:能有效防止因多線程搶奪資源造成的數據安全問題
- 缺點:需要消耗大量的CPU資源
互斥鎖的使用前提:多條線程搶奪同一塊資源
互斥鎖的示例代碼
#import "ViewController.h"
@interface ViewController ()
/** 售票機1*/
@property (strong,nonatomic) NSThread *threadOne;
/** 售票機2*/
@property (strong,nonatomic) NSThread *threadTwo;
/** 售票機3*/
@property (strong,nonatomic) NSThread *threadThree;
/** 售票機4*/
@property (strong,nonatomic) NSThread *threadFour;
/** 售票機5*/
@property (strong,nonatomic) NSThread *threadFive;
/** 數量*/
@property (assign,nonatomic) NSInteger count;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//創(chuàng)建線程
self.threadOne = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"one"];
self.threadTwo = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"two"];
self.threadThree = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"three"];
self.threadFour = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"four"];
self.threadFive = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"five"];
self.count = 100;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//開始線程
[self.threadOne start];
[self.threadTwo start];
[self.threadThree start];
[self.threadFour start];
[self.threadFive start];
}
- (void)run:(NSString *)param
{
while (1) {
//self是鎖對象
@synchronized(self)
{
if (self.count > 0) {
_count--;
NSLog(@"%zd-----%@",self.count,[NSThread currentThread]);
}
else
{
NSLog(@"賣完了----%@",[NSThread currentThread]);
break;
}
}
}
}
@end
下載網絡數據
NSURL *url = [NSURL URLWithString:@"url"];
NSDate *begin = [NSDate date];
NSData *data = [NSData dataWithContentsOfURL:url];