OC多线程

&什么是死锁,怎么解决死锁
死锁的四个条件:1.互斥:一个资源每次只能被一个进程使用、相互不可剥夺:进程已经获得的资源,在未使用玩之前,不能强行剥夺。3、循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。4、请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
解决死锁,可以通过设置信号量来防止死锁,只要上述条件有一个不满足,就不会发生死锁。

技术要点:

一 线程创建与启动
线程类 NSThread

包含如下线程操作方法:

 //返回当前线程
+ (NSThread *)currentThread;          

// 通过类方法创建一个线程
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;

// 判断是否为多线程
+ (BOOL)isMultiThreaded;

- (NSMutableDictionary *)threadDictionary;

+ (void)sleepUntilDate:(NSDate *)date;

+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

//  退出线程
+ (void)exit;

// 线程属性值
+ (double)threadPriority ;
+ (BOOL)setThreadPriority:(double)p ;

// 线程函数地址
+ (NSArray *)callStackReturnAddresses;

// 设置与返回线程名称
- (void)setName:(NSString *)n;
- (NSString *)name;

// 线程堆栈
- (NSUInteger)stackSize;
- (void)setStackSize:(NSUInteger)s;

// 判断当前线程是否为主线程
- (BOOL)isMainThread;
+ (BOOL)isMainThread;

+ (NSThread *)mainThread;

// 线程对象初始化操作   (通过创建线程对象 ,需要 手工指定线程函数与各种属性)
- (id)init;

// 在线程对象初始化时创建一个线程(指定线程函数)
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;

// 是否在执行
- (BOOL)isExecuting;

// 是否已经结束 
- (BOOL)isFinished;

// 是否取消的
- (BOOL)isCancelled;

// 取消操作
- (void)cancel;

// 线程启动
- (void)start;

- (void)main;    // thread body method

推荐方式

// 通过类方法创建一个线程
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;

// 在线程对象初始化时创建一个线程(指定线程函数)
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;

主要通过selector:(SEL)selector 指定个功能函数,系统使其与主线程分开运行,以达到多线程的效果.

以上方式创建线程,非类方法创建需要调用 start才能让线程真正运行起来.

当多个线程同时运行,就会出现访问资源的同步问题

二 线程同步操作

要说明线程的同步与锁,最好的例子可能就是多个窗口同时售票的售票系统了。我们知道在java中,使用synchronized来同步,而iphone虽然没有提供类似java下的synchronized关键字,但提供了NSCondition对象接口。查看NSCondition的接口说明可以看出,NSCondition是iphone下的锁对象,所以我们可以使用NSCondition实现iphone中的线程安全。这是来源于网上的一个例子:
  SellTicketsAppDelegate.h 文件
  // SellTicketsAppDelegate.h
  import 
  @interface SellTicketsAppDelegate : NSObject {
  int tickets;
  int count;
  NSThread* ticketsThreadone;
  NSThread* ticketsThreadtwo;
  NSCondition* ticketsCondition;
  UIWindow *window;
  }
  @property (nonatomic, retain) IBOutlet UIWindow *window;
  @end
  SellTicketsAppDelegate.m 文件
  // SellTicketsAppDelegate.m
  import "SellTicketsAppDelegate.h"
  @implementation SellTicketsAppDelegate
  @synthesize window;
  - (void)applicationDidFinishLaunching:(UIApplication *)application {

〖黑软手机资讯频道〗
  
  tickets = 100;
  count = 0;
  // 锁对象
  ticketCondition = [[NSCondition alloc] init];
  ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
  [ticketsThreadone setName:@"Thread-1"];
  [ticketsThreadone start];
  ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
  [ticketsThreadtwo setName:@"Thread-2"];
  [ticketsThreadtwo start];
  //[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
  // Override point for customization after application launch
  [window makeKeyAndVisible];
  }
  - (void)run{
  while (TRUE) {
  // 上锁
  [ticketsCondition lock];
  if(tickets > 0){
  [NSThread sleepForTimeInterval:0.5];
  count = 100 - tickets;
  NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);
  tickets--;
  }else{
  break;
  }
  [ticketsCondition unlock];
  }
  }
  - (void)dealloc {
  [ticketsThreadone release];
  [ticketsThreadtwo release];
  [ticketsCondition release];
  [window release];
  [super dealloc];
  }
四 线程池 NSOperation
NSInvocationOperation是 NSOperation的子类 具体使用代码

// 建立一个操作对象 
NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myTaskMethod:) object:data];

// 将操作对象 加到系统已经的操作对列里, 这时候 myTaskMethod以一个线程的方式与主线程分开执行.
[[MyAppDelegate sharedOperationQueue] addOperation:theOp];

// 这个是真正运行在另外一个线程的“方法”
- (void)myTaskMethod:(id)data
{
    // Perform the task.
}

main函数中其实只需要写你要在另外一个进程里面作的事情。比如对于我来说,我常常只是作一个简单的事情,那我会用NSInvocationOperation,NSOperation的简化版。比如说:

NSInvocationOperation *aOpt = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomeThing) object:nil];   - (void)doSomeThing { //读取大量大延迟数据等等 //可以使用performSelectorOnMainThread来将得来的数据返回到主线程 }

在doSomeThing函数里面,我可以从网上读取一些东西,但是读取是需要占用时间,而堵塞主线程的。而使用NSOperation这样使用就不会了。

而如果是NSOperation,虽然复杂了一些,又是做一个NSOperation的子类。其实main函数做得事情和doSomeThing是一抹一样的。只不过如果你制作这个子类,你对其操作的内容可以更多,可以制作更复杂的读取,载入操作等等,而且你可以重复使用这个类功能阿。再者,NSOperation也提供了对runtime操作的支持,不过那就太麻烦了,一般不大用的上。

 

以上是使用系统操作对列,可以使用 NSOperationQueue创建自己的线程对列

NSOperationQueue *operationQueue; 
        operationQueue = [[NSOperationQueue alloc] init]; //初始化操作队列
        [operationQueue setMaxConcurrentOperationCount:n]; // 可以设置队列是同时被处理的“操作数       

 [operationQueue addOperation:otherOper];

线程创建与撤销遵循 OC的内存管理规则.

实例:

Thread.h:

#import <Foundation/Foundation.h>

@interface Thread : NSObject

-(id)CreatThread;
-(id)MyThreadMainRoutine;

@end

Thread.m:

#import "Thread.h"

@implementation Thread
{
    NSArray *array;
}
-(void)CreatThread
{
    NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(MyThreadMainRoutine) object:nil];
    [thread start];
    array=[[NSArray alloc]initWithObjects:@"1",@"2", nil];
    [NSThread detachNewThreadSelector:@selector(MyThreadMainRoutine:) toTarget:self withObject:array];
}

-(void)MyThreadMainRoutine:(NSArray *)array
{
//    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
    NSLog(@"isMutiThread:%d",[NSThread isMultiThreaded]);
    NSLog(@"%@",array);
//    [pool release];
}
@end

SellTicket.h:

#import <Foundation/Foundation.h>

@interface SellTicketAppDelegate : NSObject
{
    int tickets; //当前票数
    int count;   //售出的票数
    NSThread *thread1; //一卖票点
    NSThread *thread2; //二卖票点
    //加锁
    NSCondition *ticketCondition;
}

@property int tickets;
@property int count;

-(void)applicationDidFinishLaunching;
-(void)run;
@end

SellTicket.m:

#import "SellTicketAppDelegate.h"

@implementation SellTicketAppDelegate

@synthesize tickets;
@synthesize count;

-(void)applicationDidFinishLaunching
{
    tickets=100;
    count=0;
    ticketCondition = [[NSCondition alloc] init];
    thread1=[[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    [thread1 setName:@"Thread-1"];
    [thread1 start];
    //[NSThread sleepForTimeInterval:1];
    thread2=[[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    [thread2 setName:@"Thread-2"];
    [thread2 start];
}
-(void)run
{
    while (TRUE) {
        [ticketCondition lock];//加锁
        if (tickets>0) {
            [NSThread sleepForTimeInterval:0.1];//延时5秒
            count=100-tickets;
            NSLog(@"已经售出票:%d 余票:%d 当前线程:%@",count,tickets,[[NSThread currentThread]name]);
            tickets--;
        }
        else{
            break;
        }

        [ticketCondition unlock];//解锁
    }
}

-(void)dealloc
{
    [thread1 release];
    [thread2 release];
    [super dealloc];
}
@end

main:

#import <Foundation/Foundation.h>

#import "SellTicketAppDelegate.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {

//        [[NSThread currentThread]setName:@"mainThread"];
//        NSLog(@"%@",[[NSThread currentThread]name]);
//        NSLog(@"main Thread will sleep 3s");
//        [NSThread sleepForTimeInterval:3];
//        NSLog(@"hello world!main Thread wake up");

//        Thread *mythread=[[Thread alloc]init];
//        [mythread CreatThread];
//        if ([NSThread isMultiThreaded]) {
//            NSLog(@"hello world");
//        }
//        [NSThread sleepForTimeInterval:3];

        NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
        //实例化一个售票对象
        SellTicketAppDelegate *sell=[[SellTicketAppDelegate alloc]init];
        //售票
        [sell applicationDidFinishLaunching];
        [NSThread sleepForTimeInterval:30];
        [pool release];
        return 0;

    }

}

结果:

2013-07-30 17:19:22.313 7.30多线程[2391:1903]
已经售出票:0 余票:100 当前线程:Thread-1

2013-07-30 17:19:22.416 7.30多线程[2391:2103]
已经售出票:1 余票:99 当前线程:Thread-2

...

...

2013-07-30 17:19:32.276 7.30多线程[2391:1903]
已经售出票:98 余票:2 当前线程:Thread-1

2013-07-30 17:19:32.377 7.30多线程[2391:2103]
已经售出票:99 余票:1 当前线程:Thread-2

时间: 2024-09-12 22:51:36

OC多线程的相关文章

运用js教你轻松制作html音乐播放器_javascript技巧

用HTML做了个音乐播放器,可以循环播放,选择歌曲,以及自动播放下一首,运用了js和json知识,下面是效果图和源码,有兴趣的可以试试哦 效果图: 源码:html <span style="color:#999999;"><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>音乐播放器</title> <sc

iOS ReactiveCocoa 最全常用API整理(可做为手册查询)

本文适合有一定RAC基础的童鞋做不时的查询,所以本文不做详细解释. 一.常见类 1.RACSiganl 信号类. RACEmptySignal :空信号,用来实现 RACSignal 的 +empty 方法: RACReturnSignal :一元信号,用来实现 RACSignal 的 +return: 方法: RACDynamicSignal :动态信号,使用一个 block - 来实现订阅行为,我们在使用 RACSignal 的 +createSignal: 方法时创建的就是该类的实例: R

OC中多线程的创建方法

方法一: NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(mutableThread) object:nil]; 方法二: [NSThread detachNewThreadSelector:@selector(mutableThread) toTarget:self withObject:nil]; 方法三: [self performSelectorInBackground:@selector(mu

OC之@property和@synthesize

在OC中经常使用get和set方法,但是当成员变量太多的时候,就要敲很多行get和set方法.在xcode4.4之前,为了简洁代码,可以使用@property声明get和set方法: @property int age; 就相当于: - (void)setAge:(int)age; -(int)age; 后面代码可以就当作正常写了get和set方法一样去调用- (void)setAge:intage;和-(int)age;. 假设_age为成员变量,当然也可以使用@synthesize去代替写出

OC面试题[搜集]

浅复制和深复制的区别?//浅拷贝和深拷贝 答案:浅层复制(copy):只复制指向对象的指针,而不复制引用对象本身.//通过对象的指针来访问这个对象 深层复制(mutableCopy):复制引用对象本身 意思就是有个A对象,复制一份后得到A_copy对象后,对于浅复制来说,A和A_copy指向的是同一个内存资源,复制的只不过是是一个指针,对象本身资源 还是只有一份,那如果我们对A_copy执行了修改操作,那么发现A引用的对象同样被修改,这其实违背了我们复制拷贝的一个思想.深复制就好理解了,内存中存

OC内存管理

一.基本原理 (一)为什么要进行内存管理. 由于移动设备的内存极其有限,所以每个APP所占的内存也是有限制的,当app所占用的内存较多时,系统就会发出内存警告,这时需要回收一些不需要再继续使用的内存空间,比如回收一些不再使用的对象和变量等. 管理范围:任何继承NSObject的对象,对其他的基本数据类型无效. 本质原因是因为对象和其他数据类型在系统中的存储空间不一样,其它局部变量主要存放于栈中,而对象存储于堆中,当代码块结束时这个代码块中涉及的所有局部变量会被回收,指向对象的指针也被回收,此时对

浅谈OC内存管理

一.基本原理 (一)为什么要进行内存管理. 由于移动设备的内存极其有限,所以每个APP所占的内存也是有限制的,当app所占用的内存较多时,系统就会发出内存警告,这时需要回收一些不需要再继续使用的内存空间,比如回收一些不再使用的对象和变量等. 管理范围:任何继承NSObject的对象,对其他的基本数据类型无效. 本质原因是因为对象和其他数据类型在系统中的存储空间不一样,其它局部变量主要存放于栈中,而对象存储于堆中,当代码块结束时这个代码块中涉及的所有局部变量会被回收,指向对象的指针也被回收,此时对

iOS开发多线程篇—线程安全

一.多线程的安全隐患 资源共享 1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源 比如多个线程访问同一个对象.同一个变量.同一个文件 当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题 示例一: 示例二: 问题代码: 1 // 2 // YYViewController.m 3 // 05-线程安全 4 // 5 // Created by apple on 14-6-23. 6 // Copyright (c) 2014年 itcase. All rights res

[c/c++/OC]高质量的面试题及答案及注解

  一.  选择题 C语言: 1. 声明语句为int a[3][4]; 下列表达式中与数组元素a[2][1]等价的是( A ). A.*(a[2]+1)      B.a[9]   C.*(a[1]+2)         D.*(*(a+2))+1  a[2] <==> *(a+2)是等价的 C两个数反过来了,D.1放进去 2.请问经过表达式a = 5 ? 0 : 1的运算,变量a的最终值是( C ) A.6      B.1       C.0       D.true  前者为真 3. 下