多线程知识

同步:多个任务依次按顺序执行

异步:多个任务可以时执行

进程:一个正在运行的应用程序就是一个进程,为应用开辟内存空间

线程:一个进程可以有多个线程,是进程的基本执行单元,执行应用的代码/任务

NSThread:

    创建线程

    方法一:对象方法

        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(demo:) object:@"mm"];

        [thread start];

    方法二:类方法

        [NSThread detachNewThreadSelector:@selector(demo:) toTarget:self withObject:@"mm"];

    方法三

        [self performSelectorInBackground:@selector(demo:) withObject:@"mm"];

        -(void)demo:(NSString *)str{

            NSLog(@"%@--%@",[NSThread currentThread],str);

            }

pthread:

        创建线程:

        NSLog(@"--%@--",[NSThread currentThread]);

        NSString *str = @"mm";

        pthread_t ID;

        int result = pthread_create(&ID, NULL, demo, (__bridge void *)(str));

        if (result == 0) {

            NSLog(@"成功 ");

    

        }else{

            NSLog(@"失败");

            }

        要调用函数

        void* demo (void *perme){

                NSString *str = (__bridge NSString *)(perme);

                NSLog(@"%@ %@",[NSThread currentThread],str);

                return NULL;

        }

线程状态(五个):新建-就绪-运行-阻塞-死亡

 例子:

新建:NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(demo:) object:@"mm"];

就绪: [thread start]

运行状态:(计算机决定,程序员不可控)

阻塞:  [NSThread sleepForTimeInterval:3];

死亡:  [NSThread exit]

NSThread线程属性:

thread.name:线程名称

thread.stackSize 线程在内存所占内存大小

thread.threadPriority 优先级(只是增大该线程的调用频率,不能保证限执行完毕) 取值范围(0,1),默认为0.5;

 //多线程共享资源问题

NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:@"mm"];

[thread1 start];

NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(demo) object:@"mm"];

[thread2 start];

 int count;

-(void)demo{

    while (YES) {

        if (count > 0) {

            count -= count;

            NSLog(@"%d",count);

        }else{

            NSLog(@"结束");

            break;

        }

    }

}

 会出现资源混乱:解决方法(互斥锁:使用的技术就是线程同步技术)能够有效防止多线程抢夺资源造成的数据安全问题

线程同步:多线程按顺序的执行任务;

互斥锁:@synchronized(1.必须继承与NSObject 2.必须是全局变量<一般设为self>) {

    要执行代码;

}

注意:加锁后线程的执行效率会比不加锁低,但保证了同时操作全局变量的安全性

posted @ 2016-07-18 10:43  mm0322  阅读(103)  评论(0编辑  收藏  举报