iOS 开发成长中心iOS 你不知道的新鲜事iOS Developer

iOS开发多线程--NSThread

2016-11-20  本文已影响62人  爱吃鱼的小灰

多线程简介

NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(thread3) object:nil];
[thread setName:@"thread3"];
    [thread start];
2.2 监听线程结束
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(myThreadFinish:) name:NSThreadWillExitNotification object:nil];

    - (void)myThreadFinish:(NSNotification *)notification
    {
         NSThread *thread = [notification object];
            if ([thread.name isEqualToString:@"thread3"])
         {
                    NSLog(@"thread3 finish!");
            }
            NSLog(@"thread ===%@",thread);
    }
 2.3 线程间通讯
    - (void)thread4
    {
            for (int i = 0; i<10; i++)
            {
                    NSLog(@"thread4  i===%d",i);
                    [NSThread sleepForTimeInterval:1.0];
        
             if (i == 8)
              {
                     //给_thread5发cancel消息.仅仅只是发消息,处不处理,由_thread5自己决定
                     [_thread5 cancel];
              }
            }
    }

    - (void)thread5
    {
            int i = 0;
            while (1)
            {
                    NSLog(@"thread5===%d",i);
                [NSThread sleepForTimeInterval:1.0];
                i++;
                    //如果thread5 接收到了cancel消息,就退出
                 if ([[NSThread currentThread]isCancelled])
                {
                     NSLog(@"thread5  exit");
                    //执行线程退出
                    [NSThread exit];
                    }
        }
    }
2.4 线程锁
```

_sumLock = [[NSLock alloc]init];
_sum = 0;

[_sumLock lock];
        _sum ++;
        [NSThread sleepForTimeInterval:1.0];
        [_sumLock unlock];
    2.5 子线程刷新UI
_progress = [[UIProgressView alloc]initWithFrame:CGRectMake(100, 100, 200, 30)];
         [self.view addSubview:_progress];

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

- (void)myThread
        {
             for (int i=1; i<11; i++)
             {
                 [self performSelectorOnMainThread:@selector(myMain:) withObject:@(i) waitUntilDone:YES];
                 [NSThread sleepForTimeInterval:1];
            }
        }

    - (void)myMain:(NSNumber *)number
    {
            NSLog(@"number==%@",number);
            [_progress setProgress:number.floatValue*0.1 animated:YES];
    }
上一篇 下一篇

猜你喜欢

热点阅读