• NSThread多线程总结(一)


    一: 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:占用内存大,线程安全不适合移动设备
     
     
     
     
     
     
     
     
     
     
     
     
  • 相关阅读:
    Java笔记(一)Eclipse 操作MySQL数据库的效率问题
    C# 笔记(六)关于switch 语句
    C# 笔记(五)关于static
    arcgis server 9.3初步
    C# 笔记(三)关于结构体变量
    OpenBSD随笔(一)
    Windows 脚本WSH
    Java笔记(二)Eclipse 连接SQlServer
    ArcGIS Server 9.3 JavaScript API实战(二)一个具体的小系统示例介绍
    C#笔记(二)类型转换
  • 原文地址:https://www.cnblogs.com/arenouba/p/5460382.html
Copyright © 2020-2023  润新知