ios-UI高级 多线程的互斥解决

本文介绍如何在iOS开发中使用多线程,并通过互斥锁解决多线程访问同一资源时产生的安全隐患。通过具体代码示例展示了如何创建线程、启动线程以及使用互斥锁保护共享资源。

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

1、控制线程状态

· 启动线程
- (void)start;

· 阻塞线程
+ (void)sleepUntilDate:(NSDate *)date;
- (void)sleepForTimeInterval:(NSTimeInterval *)interval;

· 强制停止线程
+ (void)exit;  

注:一旦线程停止(死亡)了,就不能再次开启任务。
 2、多线程的安全隐患
· 资源共享
 一块资源可能会被多个线程共享,即多个线程可能访问同一块资源;比如多个线程同时访问一个对象,这样就存在安全隐患
 3、安全隐患的解决方法--互斥锁
 · 互斥锁使用格式
 @synchronized(锁对象) {
  // 需要锁定的代码
 }
 注意:锁定一份代码的锁必须是同一把锁才能达到目的

 互斥锁的优缺点:
 优点:能有效防止因多线程抢夺资源造成的数据安全问题
 缺点:需要消耗大量的CPU资源

 互斥锁的使用前提是:多条线程同时访问同一资源

 互斥锁也称线程同步:即多条线程在同一条线上执行(按顺序的执行任务)

ViewController.m文件中:

@interface ViewController ()

// 创建4个进程

@property(nonatomic,strong) NSThread *thread1;

@property(nonatomic,strong) NSThread *thread2;

@property(nonatomic,strong) NSThread *thread3;

@property(nonatomic,strong) NSThread *thread4;

@property(nonatomic,assign) NSInteger moneyValue;

@end


@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    //初始化进程

    self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(takeMoney) object:nil];

    self.thread1.name = @"路人1";

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

    self.thread2.name = @"路人2";

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

    self.thread3.name = @"路人3";

    self.thread4 = [[NSThread alloc] initWithTarget:self selector:@selector(takeMoney) object:nil];

    self.thread4.name = @"路人4";

    

}


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

    // 启动进程

    [self.thread1 start];

    [self.thread2 start];

    [self.thread3 start];

    [self.thread4 start];

}


-(void)takeMoney{

    self.moneyValue = 6000;

    

    while (1) {

        //互斥锁

        @synchronized(self) {

            if (self.moneyValue > 0) {

                NSInteger value = self.moneyValue;

                self.moneyValue = value - 200;

                NSLog(@"%@取钱后,取款机还剩下%ld",[NSThread currentThread].name,self.moneyValue);

            }else {

            NSLog(@"取款机没有余额了");

            break;

            }

        }

    }

}

结果截图:



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值