概述
- 多线程概念
- OC中线程的使用
- 线程锁
线程:是操作系统能够进行运算调度的最小单位。
多线程简单的说就是为了各个任务执行期间不要相互打扰。
无论是iOS还是Android还是H5涉及到与用户交互的系统中(GUI),UI线程中进行视图的刷新工作,UI线程中不能进行其他耗时操作(耗时操作导致屏幕卡死)。
线程锁:为了让多个线程在操作同一个数据源的时候,数据源的数据能够保证同一时间点只能被一个线程操作。
示例
- 展示线程创建和启动的两种方式
- 线程加锁
仔细看注释,很简单
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
//定义俩个线程
NSThread* _th01;
NSThread* _th02;
//定义一个计数器
NSInteger _count;
//定义一个线程锁对象
NSLock* _lock;
}
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//添加三个按钮
//展示线程创建和启动的两种方式
//线程加锁
NSArray* array = [NSArray arrayWithObjects:@"启动线程",@"启动线程01",@"启动线程02", nil];
for (int i=0; i<array.count; i++) {
UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100+80*i, 80, 40);
[btn setTitle:array[i] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
btn.tag = 101 + i;
[self.view addSubview:btn];
}
//实例化线程锁
_lock = [NSLock new];
}
-(void) pressBtn:(UIButton*) btn{
NSInteger tag = btn.tag;
if (tag == 101) {
NSLog(@"btn01");
//创建并启动线程
[NSThread detachNewThreadSelector:@selector(actT) toTarget:self withObject:nil];
}else if (tag == 102){
//创建一个线程实例
//p1:线程函数运行实例
//p2:线程处理函数
//p3:线程参数
_th01 = [[NSThread alloc] initWithTarget:self selector:@selector(actT01:) object:nil];
//启动并运行
[_th01 start];
}else if (tag == 103){
_th02 = [[NSThread alloc] initWithTarget:self selector:@selector(actT02:) object:nil];
//启动并运行
[_th02 start];
}
}
-(void)actT01:(NSThread*)th{
NSLog(@"actT01");
int i=0;
while (true) {
if (i>=10000) {
break;
}
i++;
//线程加锁,保证线程安全。
[_lock lock];
_count++;
[_lock unlock];
NSLog(@"_count01==%d",_count);
}
}
-(void) actT02 :(NSThread*)th{
int i=0;
while (true) {
if (i>=10000) {
break;
}
i++;
[_lock lock];
_count++;
[_lock unlock];
NSLog(@"_count02==%d",_count);
}
}
-(void) actT {
int i = 0;
while (true) {
if(i>=100000){
break;
}
i++;
NSLog(@"i=%d",i);
}
}
@end