ios学习 多线程NSThread 基本属性

来源:互联网 发布:网络借贷不还会坐牢吗 编辑:程序博客网 时间:2024/05/29 08:15

- (void)viewDidLoad {

    [superviewDidLoad];

}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [selfdemo2];

}


-(void)demo{

    //第一种方法,需启动

    NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(task)object:nil];

    thread.name =@"one";

    [thread start];

    

    NSThread *thread2 = [[NSThreadalloc]initWithTarget:selfselector:@selector(task)object:nil];

    thread2.name =@"two";

    [thread2 start];

    

//    //第二种方法,无需启动

//    [NSThread detachNewThreadSelector:@selector(task) toTarget:self withObject:nil];

    

//    //第三种方法,隐式创建线程

//    [self performSelectorInBackground:@selector(task) withObject:nil];

}


//优先级

-(void)demo2{

    NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(task)object:nil];

    //线程的优先级,取值范围0.0 - 1.0;默认为0.5

    thread.threadPriority =0;

    //线程命名,方便调试

    thread.name =@"-----------one";

    [thread start];

    

    NSThread *thread2 = [[NSThreadalloc]initWithTarget:selfselector:@selector(task)object:nil];

    thread2.name =@"two";

    [thread2 start];

}


-(void)task{

//    NSLog(@"task is running %@",[NSThread currentThread]);

//    

//    NSLog(@"睡了");

//    //阻塞

////    [NSThread sleepForTimeInterval:2];  //睡眠2

//    [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:5]];  //距离当前时间5

//    

//    NSLog(@"醒了");

//    //手动杀死线程

//    [NSThread exit];

//    NSLog(@"died");

    

    for (int i =0; i < 20; i++) {

        NSLog(@"%@ %d", [NSThreadcurrentThread],i);

    }

}

0 0
原创粉丝点击