NSThread:
1:NSThread基本概念
2:NSThread的创建
3:NSThread的使用
基本函数:
1:inITWithTarget:创建线程
2:detachNewThreadSelector:类方法创建并启动线程
3:lock:线程加锁
4:unlock:线程解锁
5:sleepForTimeInterval:线程休眠
具体实现如下:
//
// ViewController.m
// NSThread
//
// Created by 刘群 on 2018/1/22.
// Copyright © 2018年 刘群. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
{
//定义两个线程对象
NSThread *_thread1;
NSThread *_thread2;
//计数器
NSInteger _count;
//线程锁对象
NSLock *_lock;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *arr = @[@"启动线程",@"启动线程1",@"启动线程2"];
for (int i=0; i<3; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(50, 30+i*80, 80, 40);
[btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:arr[i] forState:0];
[self.view addSubview:btn];
btn.tag = 100+i;
}
_lock = [[NSLock alloc]init];
}
- (void)pressBtn:(UIButton*)btn{
if (btn.tag == 100) {
NSLog(@"按钮一按下");
//创建一个线程函数
//P1:线程对象运行函数的拥有者
//P2:线程处理函数
//P3:线程参数
NSThread *newThr = [[NSThread alloc]initWithTarget:self selector:@selector(actThread:) object:nil];
//启动并且运行函数
[newThr start];
}else if (btn.tag == 101){
NSLog(@"按钮二按下");
//创建并且启动线程
[NSThread detachNewThreadSelector:@selector(actThread2:) toTarget:self withObject:nil];
}else if(btn.tag == 102){
NSLog(@"按钮三按下");
_thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(actThread3:) object:nil];
[_thread2 start];
}
}
//第一个按钮
- (void)actThread:(NSThread*)thread{
int i = 0;
while (true) {
i++;
NSLog(@"%d",i);
}
}
//第二个按钮
- (void)actThread2:(NSThread*)thread2{
int i = 0;
while (true) {
i++;
if (i>=10001) {
break;
}
//加锁确保最终的准确性
[_lock lock];
_count++;
[_lock unlock];
NSLog(@"thread2=========%ld",_count);
}
NSLog(@"final=====%ld",_count);
}
//第三个按钮
- (void)actThread3:(NSThread*)thread3{
int i = 0;
while (true) {
i++;
if (i>=10001) {
break;
}
[_lock lock];
_count++;
[_lock unlock];
NSLog(@"thread3======%ld",_count);
}
NSLog(@"final=====%ld",_count);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
//在没有加锁之前,_count++在两个线程同时进行计算后,得到的结果不会是20000,通过多次运算就会有多个结果,原因是由于两个线程是同步运行,在同步运行的时候存在数据的重叠性,那么解决这个同时运行中数据的重叠的关键技术就是使用 线程加锁,通过使用线程加锁达到每个线程独立运行,独立运行的意思是:当前线程运行完后系统通过调度算法再去调度另一个线程,线程之间达到理论上的异步进行,从而达到数据运算的准确性。