thread一些基本的用法
1.Thread的用法
1.1没什么详细解释,直接看用法
1.2代码
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(run) object:@"HYL"];
thread.name=@"hyl";
[thread start];
}
-(void) run{
NSLog(@"fdsff");
NSLog(@"%@",[NSThread mainThread]);
NSLog(@"%i",[NSThread isMainThread]);
NSThread *current=[NSThread currentThread];
NSLog(@"%@",current);
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self performSelectorInBackground:@selector(run) withObject:nil];
}
2.看看线程开启过程的一些状态
2.1图片
3.线程安全
3.1线程安全是有多个线程访问同一个资源所产生的问题
3.2解决:线程同步的应用,耗资源,所以:不是多个线程同时访问一个资源,无需加锁。
3.3具体看代码
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.saleMan1 start];
[self.saleMan2 start];
[self.saleMan3 start];
}
-(void) run{
while (1) {
@synchronized(self) {
if (self.counts>0) {
--self.counts;
NSLog(@"%@ %li",[NSThread currentThread],(long)self.counts);
} else {
NSLog(@"end");
break;
}
}
}
}
3.31锁定一份代码只能用唯一一个锁对象,否则无效
3.4不加锁与加锁后的结果
3.41不加锁

3.42加锁

3.43原子与非原子属性
- 1.线程安全,非常耗资源
- 2.非线程安全,适合移动设备
- 3.使用选择
- 3.1.所有的属性都声明为 nonatomic
- 3.2.尽量避免多线程抢夺一块资源
- 3.3.尽量将加锁,资源抢夺业务逻辑让服务器端处理
4.源代码详细地址