一个有趣的多线程应用实例

这个实例主要实现了隔相同的时间一张张加载图片在用for循环创建6个不同的图片视图上,且点击屏幕可使未完成的进程被取消,并退出即未加载的图片停止加载,有兴趣的朋友可以一试。(相应的注意点都已经在代码中注释)


#import "ViewController.h"

#define kUrl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943"


@interface ViewController (){

    int tagValue;

    UIImage *image;

    NSMutableArray *threadArray;

}


@end


@implementation ViewController


-(void)viewDidLoad{

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    tagValue = 100;

    threadArray = [NSMutableArray array];

    self.edgesForExtendedLayout = 0;

    self.title = @"多张图片";

    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:24],NSForegroundColorAttributeName:[UIColor greenColor]}];

    

//    创建多个UIimageview

    for (int row = 0; row<3; row++) {

        for (int list = 0; list<2; list++) {

            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10+list*200, 10+row*200, 200, 200)];

            imageView.tag = tagValue++;

            imageView.backgroundColor = [UIColor redColor];

            imageView.userInteractionEnabled = YES;

            [self.view addSubview:imageView];

        }

    }

    

//    创建多个子线程

    for (int index = 0; index<6; index++) {

        [NSThread detachNewThreadSelector:@selector(thread:) toTarget:self withObject:@(index)];

    }

}


//    通过url加载网络图片

- (void)thread:(NSNumber *)index{

    

    [threadArray addObject:[NSThread currentThread]];

    NSThread *thread = [NSThread currentThread];

    

    [NSThread sleepForTimeInterval:[index intValue]];//通过线程休眠实现顺序加载

    

    if (thread.isCancelled == YES) {

        [NSThread exit];

    }

    

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kUrl]];

    image = [UIImage imageWithData:data];

    

//    ❤️❤️回到主线程

    [self performSelectorOnMainThread:@selector(updateUI:) withObject:index waitUntilDone:YES];

}


//  更新UI

- (void)updateUI:(NSNumber *)index{

    

    UIImageView *imageV = [self.view viewWithTag:[index integerValue]+100];

    imageV.image = image;

}


//点击屏幕取消未完成的线程

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

    NSLog(@"%@",threadArray);

    for (int index = 0; index<6; index++) {

        NSThread *thread = threadArray[index];

        if (thread.isFinished == NO) {

            [thread cancel];//取消不是退出

        }

    }

}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值