iOS 多线程

iOS--多线程--NSThread

2016-02-28  本文已影响36人  STONEsh

ViewController.m#

//
//  ViewController.m
//  多线程--NSThread
//
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //---------------多线程NSThread法一 ---------------------------
    
////子线程:
//    NSThread *thr = [[NSThread alloc] initWithTarget:self selector:@selector(mutableThread) object:nil];
//    [thr start];
//    
////主线程:
//    for (int i = 0; i < 50; i ++) {
//        NSLog(@"主线程:%d", i);
//    }
    
    
    
     //---------------------多线程NSThread 法二 -------------------------
    
    
//子线程:
    [NSThread detachNewThreadSelector:@selector(mutableThread) toTarget:self withObject:nil];
    
    [self performSelectorInBackground:@selector(mutableThread) withObject:nil];
//主线程:
    for (int i = 0; i < 50; i ++) {
        NSLog(@"主线程:%d", i);
    }
    
    

}


//子线程调用方法

-(void)mutableThread{
    
    for (int i = 0; i < 50; i ++) {
        NSLog(@"多线程:%d", i);
    }
   
    BOOL isMulti = [NSThread isMultiThreaded];//判断是否是多线程
    
    if (isMulti) {
        
        NSLog(@"当前线程是多线程");
    }
    
    
//在主线程上执行refershUI方法
    [self performSelectorOnMainThread:@selector(refershUI) withObject:nil waitUntilDone:YES];//此处为YES那么 refersgUI 方法执行完才会执行打印finish的操作;No是即使refershUI没执行完打印finish的操作也会执行//refershUI执行对象为self,即当前的对象
    
    NSLog(@"finish");
 
    
}


-(void)refershUI{
    
    BOOL isMainThread = [NSThread isMainThread];
    
    if (isMainThread) {
        NSLog(@"当前线程是主线程");
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

上一篇下一篇

猜你喜欢

热点阅读