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
相關文章
相關標籤/搜索