NSThread
- 一个NSThread对象就代表一条线程
- NSThread会在执行完任务函数是被自动收回
- 一些常用的函数
//创建线程
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector() object:nil];
//object存的是参数
//修改参数名
thread.name = @"我的多线程";
//获取主线程
NSThread *thread = [NSThread mainThread];
//创建线程并自动启动
[NSThread detachNewThreadSelector:@selector() toTarget:self withObject:nil];
//隐士创建
[self performSelectorInBackground:@selector() withObject:nil];
//获取当前线程
[NSThread currentThread]
//启动线程
- (void)start;
//阻塞(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 进入阻塞状态
//停止当前正在运行的进程
+ (void)exit;
// 进入死亡状态,一旦死亡则不能重启
资源共享
- 1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源
- 当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题
解决办法互斥锁
-
互斥锁使用格式
- @synchronized(锁对象) { // 需要锁定的代码 }
- 只用一把锁,多锁是无效的
-
互斥锁的优缺点
- 优点:能有效防止因多线程抢夺资源造成的数据安全问题
- 缺点:需要消耗大量的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];
//创建线程
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];