[多线程之四]-自定义NSThread

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

@interface myThread : NSThread

-(instancetype) init;
-(instancetype) initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
-(void)main;
@end
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    NSThread* T;
    myThread* myT1;
    myThread* myT2;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //注意点1:initWithTarget用的sel最多有一个参数,可以没有,有两个能编译,但运行报错。
    T = [[NSThread alloc]initWithTarget:self selector:@selector(FunOneParam:) object:@"Hello"];
    //[T start];
    myT1 = [[myThread alloc] init];
    //注意点2:默认创建不启动
    //[myT1 start];
    //注意点3:即使创建的时候指定了sel,如果有main的话,也不执行sel
    myT2 = [[myThread alloc] initWithTarget:self selector:@selector(FunOneParam:) object:@"World"];
    [myT2 start];
    //注意点4:performSelector这个方法给自定义线程不能执行,除非打开NSRunLoop
    [self performSelector:@selector(FunOneParam:) onThread:myT2 withObject:@"1111" waitUntilDone:NO];
    // Do any additional setup after loading the view, typically from a nib.
}

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

-(void)FunNonParam
{
    NSLog(@"Non param!");
}

-(void)FunOneParam:(NSString*) Aparam
{
    NSLog(@"One param,%@",Aparam);
}
-(void)FunTwoParam:(NSString*) Aparam1
          SecParam:(NSString*) AParam2
{
    NSLog(@"Two Parms, %@;%@", Aparam1, AParam2);
}
@end

@implementation myThread
{
    NSInteger _index;
}

-(instancetype)init
{
    if (self = [super init]) {
        _index =5;
    }
    return  self;
}

-(instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
{
    _index = 5;
    return [super initWithTarget:target selector:selector object:argument];
}
-(void)main
{
    while (![self isCancelled]) {
        [NSThread sleepForTimeInterval:1];
        NSLog(@"%ld",_index);
        _index++;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值