码迷,mamicode.com
首页 > 编程语言 > 详细

NSThread多线程总结(一)

时间:2016-05-05 02:01:37      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

一: NSThread 小节
//1. object是传值的对象 创建完成后 自动启动
    [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http:"];
    //2. 第二种方式 隐事创建  也是自动启动
    [self performSelectorInBackground:@selector(download:) withObject:nil];
    //3. 一个NSThread 就代表一个线程对象  第三种 就是alloc init方式直接创建 可以直接拿到对象进行修改 ,而上面两种就不能直接修改其他属性
     NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:nil];
    thread1.name = @"aren";
    [thread1 start];
    // 睡眠5秒钟
    [NSThread sleepForTimeInterval:5];
 
二:线程安全 互斥锁
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self createThread];
   
    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sale) object:nil];
    thread1.name = @"窗口1";
    [thread1 start];
    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sale) object:nil];
    thread2.name = @"窗口2";
    [thread2 start];
    NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(sale) object:nil];
    thread3.name = @"窗口3";
    [thread3 start];
   
}

//三个线程同时执行这个方法
- (void)sale
{
    while (1) {
        // 互斥锁 优点:有效防止多线程抢夺资源造成的数据安全问题
        //缺点:需要消耗大量的cpu资源
        //互斥锁的使用前提是:多条线程抢占同一资源
        @synchronized(self) { //开始加锁 保证只有一个线程在执行
            int count = self.ticketsCount;
            if (count > 0) {
                //睡眠一会
                [NSThread sleepForTimeInterval:0.01];
                self.ticketsCount = count - 1;
                NSLog(@"%@卖了一张,还剩%d张",[NSThread currentThread].name, self.ticketsCount);
            } else {
                [NSThread  exit];
                return; //退出循环
            }

        }
    }

}
三:nonatomic 和 atomic 的区别
nonatomic:占用内存资源小,非线程安全,适合移动设备
atomic:占用内存大,线程安全不适合移动设备
 
 
 
 
 
 
 
 
 
 
 
 

NSThread多线程总结(一)

标签:

原文地址:http://www.cnblogs.com/arenouba/p/5460382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!