zoukankan      html  css  js  c++  java
  • NSThread学习

    使用多线程可以防止主线程阻塞。同时也可以将一个大的任务分成若干个小的任务去做。

    常用方法一:

    1, 首先使用  detachNewThreadSelector:toTarget:withObject:来启动一个新的线程

        [NSThread detachNewThreadSelector:@selector(addImagesWithPaths:) toTarget:self withObject:urls];

    2,在上面执行的函数中需要首先使用新的NSAutoreleasePool来管理内存,因为在线程函数中创建的任何对象在函数执行完成以后并不会得到释放,会造成内存泄漏。形式为:

       - (void)addImagesWithPaths:(NSArray *)urls
    {   
        NSInteger i, n;
        
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        [urls retain];

        n = [urls count];
        for ( i= 0; i < n; i++)
        {
            NSURL *url = [urls objectAtIndex:i];
            [self addImagesWithPath:[url path] recursive:NO];
        }

        /* update the datasource in the main thread */
        [self performSelectorOnMainThread:@selector(updateDatasource) withObject:nil waitUntilDone:YES];

        [urls release];
        [pool release];
    }

    3,  performSelectorOnMainThread 更新主界面

    - (void)updateDatasource
    {
        //-- update our datasource, add recently imported items
        [_images addObjectsFromArray:_importedImages];
        
        //-- empty our temporary array
        [_importedImages removeAllObjects];
        
        //-- reload the image browser and set needs display
        [_imageBrowser reloadData];
    }

    常用方法二:

    1,NSThread* myThread = [[NSThread alloc] initWithTarget:self   selector:@selector(doSomething:) object:nil]; //创建thread

    2,[myThread start];  //启动一个thread

    3,上锁比如典型的购票程序

       NSLock *theLock; 

      - (void)run{  while (TRUE) { 

      // 上锁  [theLock lock];  if(tickets >= 0){  

      [NSThread sleepForTimeInterval:0.09]; 

      count = 100 - tickets; 

      NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); 

      tickets--; 

      }else{ 

      break;  

      } 

    [theLock unlock];  

    }  

  • 相关阅读:
    Resharper的使用
    SQL Server 占用CPU较高的解决方法
    014 FPGA千兆网UDP通信
    012 PCIe总线的基础知识
    008 PCI设备BAR空间的初始化
    016 基于FPGA的网口通信实例设计【转载】
    015 FPGA千兆网TCP通信【转载】
    006 PCI总线的桥与配置(一)
    004 PCI Express体系结构(四)
    007 PCI总线的桥与配置(二)
  • 原文地址:https://www.cnblogs.com/lisa090818/p/3794835.html
Copyright © 2011-2022 走看看