网络多线程-NSThread的使用

#import "ViewController.h"

#import "XMGThread.h"

@interface ViewController ()


@end


@implementation ViewController


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

{

    [self createThread3];

}


//需要启动线程,可以设置线程

-(void)createThread1

{

    //1.创建线程对象

    /*

     第一个参数:目标对象self

     第二个参数:要调用的方法

     第三个参数:要调用方法的参数,nil

     */

    //当线程里面的任务执行完毕之后,线程被释放

    XMGThread *thread = [[XMGThread alloc]initWithTarget:self selector:@selector(run:) object:@"创建线程"];

    NSLog(@"%@",[NSThread mainThread]);

    

    //设置线程属性

    thread.name = @"线程A";

    thread.threadPriority = 1.0; //设置优先级 0.0~1.0 默认是0.5  最高是1.0

    //2.启动线程

    [thread start];

    

    NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:nil];

    thread2.name = @"线程B";

    thread2.threadPriority = 0.1;

    [thread2 start];

    

    NSThread *thread3 = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:nil];

    thread3.name = @"线程C";

    [thread3 start];

}

//第二种:分离出一条子线程,自动启动,不能详细的设置线程对象

-(void)createThread2

{

    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分离线程"];

}

//第三种:开启后台线程,自动启动,不能详细的设置线程对象

-(void)createThread3

{

    [self performSelectorInBackground:@selector(run:) withObject:@"123"];

}


-(void)run:(NSString *)param

{

    for (NSInteger i = 0;i<10;i++) {

        NSLog(@"%@---%@--%zd",param,[NSThread currentThread],i);

    }

}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值