网络多线程02

来源:互联网 发布:淘宝网店加盟哪家好 编辑:程序博客网 时间:2024/05/25 12:21


原子属性:在多个线程的环境下,只有一个线程同一时间能够对变量进行赋值的操作,读取没有线程的限制

 非原子属性:读取和赋值都可以是多线程
 apple
在内部也是用了一把锁->自旋锁

 自旋锁:在一个线程进行赋值操作的时候,另外一个线程会不断的判断锁的状态,直到锁打开

@property(atomic,strong).....在属性的时候是自旋锁


 同步锁:1.锁的范围没有限制2.另外一个线程仅仅是等着被CPU调度运行

 -都有性能的损耗


 @synchronized(self.obj) {//同步锁:@synchronized(任意对象){锁的代码}-互斥锁

           
if(self.i>0){
               
self.i=self.i -1;
               
NSLog(@"%@%d",[NSThreadcurrentThread],self.i);
               
continue;
            }
        }


从网络加载图片是耗时任务

  //开启线程
   
NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(downloadIMG)object:nil];
    [thread
start];
}

//下载图片-有可能是一个耗时任务,取决于网络连接质量

-(void)downloadIMG{
   
//模拟网络延时
    [
NSThreadsleepForTimeInterval:5];
   
   
//下载路径

NSString*imgAddress = @"http://npic7.edushi.com/cn/zixun/zh-chs/2015-07/13/1c96278dda3648eaa27fff8ef5141c0a.jpg";
   
NSURL *url = [NSURLURLWithString:imgAddress];
   
//网络上所有的数据都是二进制的形式
   
NSData *data = [NSDatadataWithContentsOfURL:url];
   
//把二进制数据转换成图片
   
UIImage *image = [UIImageimageWithData:data];
   
   
//线程间的通讯: 在子线程加载完,回到主线程运行 刷新UI
   

    [
self performSelectorOnMainThread:@selector(updateUI:)withObject:imagewaitUntilDone:NO];
   
}

//刷新UI
-(
void)updateUI:(UIImage*)image{
   
//UI的操作需要放到主线程去运行
   
self.imageView.image= image;
}




0 0
原创粉丝点击