Thread一些基本的用法

本文介绍了iOS开发中线程的基本用法,包括NSThread的创建与启动,并通过实例展示了线程安全问题及其解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

thread一些基本的用法
1.Thread的用法
1.1没什么详细解释,直接看用法
1.2代码
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //一个NSThread对象就代表一条线程
    //创建(局部变量,当执行完run后自动销毁)
//    NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(run) object:@"HYL"];
    thread.name=@"hyl";
    //启动线程
    [thread start];
}
-(void) run{
    NSLog(@"fdsff");
    NSLog(@"%@",[NSThread mainThread]);
    NSLog(@"%i",[NSThread isMainThread]);
    NSThread *current=[NSThread currentThread];
    NSLog(@"%@",current);
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //创建线程后自动启动线程
//    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

    //隐式创建并创建线程
    [self performSelectorInBackground:@selector(run) withObject:nil];
}
2.看看线程开启过程的一些状态
2.1图片
3.线程安全
3.1线程安全是有多个线程访问同一个资源所产生的问题
3.2解决:线程同步的应用,耗资源,所以:不是多个线程同时访问一个资源,无需加锁。
3.3具体看代码
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.saleMan1 start];
    [self.saleMan2 start];
    [self.saleMan3 start];
}
-(void) run{
    while (1) {
        @synchronized(self) {
            if (self.counts>0) {
                --self.counts;
                NSLog(@"%@  %li",[NSThread currentThread],(long)self.counts);
            } else {
                NSLog(@"end");
                break;
            }

        }
    }
}
3.31锁定一份代码只能用唯一一个锁对象,否则无效
3.4不加锁与加锁后的结果
3.41不加锁

3.42加锁

3.43原子与非原子属性
  • 1.线程安全,非常耗资源
  • 2.非线程安全,适合移动设备
  • 3.使用选择
    • 3.1.所有的属性都声明为 nonatomic
    • 3.2.尽量避免多线程抢夺一块资源
    • 3.3.尽量将加锁,资源抢夺业务逻辑让服务器端处理
4.源代码详细地址
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值