笔记-关于线程


ViewController.m


#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //线程
    //NSThread
    //创建线程第一种形式(需要手动开启关闭)
    NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadAction) object:nil];
    thread.name = @"coco1";
    NSLog(@"aaaaa:%@",[NSThread currentThread]);
    //开启线程
    [thread start];
    //关闭线程
    [thread cancel];
    //返回值BOOL类型,检测是否是主线程
    [thread isMainThread];
    
    
    
    //NSThread创建的第二种形式
    //这个方法是没有返回值的,线程自动开启
    [NSThread detachNewThreadSelector:@selector(thread2Action) toTarget:self withObject:nil];
    
   //
    NSInvocationOperation *INVOCATION = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocationAction) object:nil];
//    [INVOCATION start];
    //用NSOperationQueue管理NSInvocationOperation不要手动开启这个操作,NSInvocationOperation单独用的时候要手动开启.
    
    //NSOperationQueue操作队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
   
    //
    NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"block:%@",[NSThread currentThread]);
    }];
//    [block start];
    [queue addOperation:INVOCATION];
    [queue addOperation:block];
    
    //添加依赖关系,block先执行,invocation后执行
    [INVOCATION addDependency:block];
    
    
    
    //NSObject的后台多线程执行(NSObject自带的后台执行的方法)
    [self performSelectorInBackground:@selector(nsobjectAction) withObject:nil];
    
    
    
    
    
    
    
    
}

#pragma mark threadAction
-(void)threadAction{
    NSLog(@"c.c:%@",[NSThread currentThread]);
}

#pragma mark thread2Action
-(void)thread2Action{
    NSLog(@"a.a:%@",[NSThread currentThread]);
}

#pragma mark invocationAction
-(void)invocationAction{
    NSLog(@"invocation:%@",[NSThread currentThread]);
}

#pragma mark 模拟阻塞线程
- (IBAction)button1:(id)sender {
    for (int i = 0; i < 6000000; i++) {
        NSLog(@"%d",i);
    }
    
}

#pragma mark nsobjectAction
-(void)nsobjectAction{
    NSLog(@"nsobject:%@",[NSThread currentThread]);
}

#pragma mark 测试
- (IBAction)button2:(id)sender {
}

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

@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值