ios线程-创建及通信

来源:互联网 发布:配置java环境变量 编辑:程序博客网 时间:2024/06/05 04:18

创建、启动线程;

(1) NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];

  [thread start]; // 线程一启动,就会在线程thread中执行self的run方法


(2)创建线程后自动启动线程:[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];


3)隐式创建并启动线程:  [self performSelectorInBackground:@selector(run) withObject:nil];//子线程在后台运行


获得当前线程: NSThread *current = [NSThread currentThread];


+ (NSThread *)mainThread; // 获得主线程

- (BOOL)isMainThread; // 是否为主线程

+ (BOOL)isMainThread; // 是否为主线程


线程的调度优先级:调度优先级的取值范围是0.0 ~ 1.0,默认0.5,值越大,优先级越高:
+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;


设置线程的名字:
- (void)setName:(NSString *)n;
- (NSString *)name;


线程间通信常用方法:

   //给主线程传的方法名,参数,是否阻塞

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

//给指定线程传的方法名

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;


waitUntilDone是YES的话,子线程结束后 会阻塞主线程 走callBack方法
如果是NO的话 就不会阻塞 主线程

@synchronized:加锁

线程阻塞:

    [NSThread sleepForTimeInterval:2.0];
    //第二种设置线程阻塞2,以当前时间为基准阻塞4秒
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:4.0];
    [NSThread sleepUntilDate:date];




34     NSURL *urlstr=[NSURL URLWithString:@"fdsf"];35 36     //把图片转换为二进制的数据37     NSData *data=[NSData dataWithContentsOfURL:urlstr];//这一行操作会比较耗时38 39     //把数据转换成图片40     UIImage *image=[UIImage imageWithData:data];









0 0
原创粉丝点击