10.1 NSThread 不常用 难以管理

本文通过一个具体的iOS应用实例,介绍了如何使用NSThread在iOS中实现多线程操作。包括不同方式创建线程、更新UI进度条以及解决线程同步问题。

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

//
//  ViewController.m
//  10 NSThread
//
//  Created by Tracy on 15/5/29.
//  Copyright (c) 2015年 Tracy. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIProgressView *progressView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    [self doWork];
//    [self doWork];
//    [self doWork];
    
}
- (IBAction)useThread:(UIButton *)sender
{
    NSThread*thread=[[NSThread alloc]initWithTarget:self selector:@selector(doWork) object:nil];
    [thread start];//启动线程
    //第二种方式
    [NSThread detachNewThreadSelector:@selector(doWork) toTarget:self withObject:nil];
    //第三种方式
    [self performSelectorInBackground:@selector(doWork) withObject:nil];
}

- (IBAction)updateProgress:(UIButton *)sender
{
    [NSThread detachNewThreadSelector:@selector(updateProgressView) toTarget:self withObject:nil];
    
}
-(void)updateProgressView
{
    self.progressView.progress=0.0f;
    for (int i=0; i<100; i++) {
        [NSThread sleepForTimeInterval:0.1f];

        [self performSelectorOnMainThread:@selector(upDateUI) withObject:nil waitUntilDone:YES];
    }
}

-(void)upDateUI
{
    self.progressView.progress+=0.01;
}
-(void)doWork
{
    for (int i=0; i<30; i++) {
        [NSThread sleepForTimeInterval:0.01f];
        NSLog(@"%d thread %@",i,[NSThread currentThread]);
    }
}
- (IBAction)fetchMoney:(UIButton *)sender
{
    NSThread*husband=[[NSThread alloc]initWithTarget:self selector:@selector(fetchMoneyByWho:) object:@"husband"];
    [husband start];
    
    NSThread*wife=[[NSThread alloc]initWithTarget:self selector:@selector(fetchMoneyByWho:) object:@"wife"];
    [wife start];
    
    NSThread*dau=[[NSThread alloc]initWithTarget:self selector:@selector(fetchMoneyByWho:) object:@"dau"];
    [dau start];
}
-(void)fetchMoneyByWho:(NSString*)name
{
    static int money=10000;
//    NSLog(@"before who %@,how much %d",name,money);
//    
//    money-=2000;
//    NSLog(@"after who %@,how much %d",name,money);
 
//@synchronized 可以使线程同步,避免异步使取钱,买票等情况发生错误
   @synchronized (self)
    {
        NSLog(@"before who %@,how much %d",name,money);
        
            money-=2000;
            NSLog(@"after who %@,how much %d",name,money);

    }

}

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

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值