NSThread

 

#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
相关文章
相关标签/搜索