#import <UIKit/UIKit.h>
@interface VCRoot : UIViewController
{
//计数器
int _count ;
//线程锁
//可以对变量进行加锁操作
NSLock* _lock ;
}
@end
#import "VCRoot.h"
@interface VCRoot ()
@end
@implementation VCRoot
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//创建一个线程锁
_lock = [[NSLock alloc] init] ;
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//创建线程一
//创建一个线程
//参数一:线程执行函数的目标对象
//参数二:为线程要执行的函数
//参数三:可以传递一个参数到线程中执行
//返回一个线程对象
//仅仅创建了线程,并未立刻执行线程
[NSThread detachNewThreadSelector:@selector(updateT1:) toTarget:self withObject:nil] ;
//字典对象
//
NSDictionary* dicValue = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:0],@"SNum",
[NSNumber numberWithInt:1000000],@"ENum",nil] ;
//创建线程二
//将参数传入线程
NSThread* t2 = [[NSThread alloc] initWithTarget:self selector:@selector(updateT2:) object:dicValue] ;
//开启线程并执行线程中的函数
[t2 start] ;
}
-(void) updateT1:(id) obj
{
int i = 0 ;
while (true)
{
//对变量进行加锁操作
//可以对以下代码操作进行原子级绑定
//不允许其他线程进行操作
[_lock lock] ;
_count++ ;
//直到操作结束之后,将线程锁解开
//允许其他线程操作
[_lock unlock] ;
i++ ;
if (i == 1000000)
{
//break ;
NSLog(@"r1 = %d",_count) ;
//获得执行当前函数的线程
NSThread* curT = [NSThread currentThread] ;
//通知系统将当前的线程取消
[curT cancel] ;
//当前线程已经被取消
if ([curT isCancelled] == YES)
{
//直接退出线程,直接将当前的线程结束掉
//系统直接停止当前线程
[NSThread exit] ;
}
}
//NSLog(@"count1 = %d",_count) ;
}
}
//线程二的参数
-(void) updateT2:(id) obj
{
NSLog(@"dic = %@",obj) ;
NSDictionary* dic = (NSDictionary*) obj ;
int start = [[dic objectForKey:@"SNum"] intValue] ;
int end = [[dic objectForKey:@"ENum"] intValue] ;
//start = 0
//end = 100000
for (int i = start; i < end; i++)
{
[_lock lock] ;
_count++ ;
[_lock unlock] ;
//NSLog(@"_count2 = %d",_count) ;
}
NSLog(@"r2 = %d",_count) ;
}
@end