OC中多线程详解

来源:互联网 发布:jquery 删除二维数组 编辑:程序博客网 时间:2024/09/21 09:19

来自:http://www.xuebuyuan.com/1491352.html


第一、多线程实现的三种方式:

1NSThread *thread=[[NSThread alloc] initWithTarget:selfselector:@selector(mutableThread:)object:@"hello"];

   [thread start];


2[NSThreaddetachNewThreadSelector:@selector(mutableThread:)toTarget:selfwithObject:nil];


3[self performSelectorInBackground:@selector(mutableThread:)withObject:nil];



第二、利用多线程异步加载图片

-(void)setImageWithURL:(NSURL *)url

{

        //  获取队列

        dispatch_queue_t queue = dispatch_queue_create("loadImage",NULL);

        // async:异步  sync:同步 

        dispatch_async(queue, ^{

                NSData *data=[NSDatadataWithContentsOfURL:url];

                UIImage *image=[UIImage imageWithData:data];

                dispatch_sync(dispatch_get_main_queue(), ^{

                        self.image=image;

                    });

                self.image=image;

            });

}


第三、NSRunloop

一个run loop就是一个事件处理循环,用来不停的调配工作以及处理输入事件。使用run loop的目的是使你的线程在有工作的时候工作,没有的时候休眠。NSRunloop可以保持一个线程一直为活跃状态,不会马上销毁。

在多线程中使用定时器必须开启Runloop,因为只有开启Runloop保持线程为活跃状态,定时器才能运行正常。

- (void)viewDidLoad

{

    [super viewDidLoad];

    //self.view.backgroundColor=[UIColor blueColor];

    [self performSelectorInBackground:@selector(multithread) withObject:nil];

}


-(void)multithread

{

    NSLog(@"HE");

    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];

    [[NSRunLoop currentRunLoop]run];

}


-(void)timeAction

{

    NSLog(@"HELLO");

}

原创粉丝点击