概述
- 多線程概念
- 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