例如:
// 这种创建线程⾃自动就运⾏行
(1)、动态创建
NSThread *t2 = [[NSThread alloc] initWithTarget:self selector:@selector(threadMain2:) object:nil];
// 设置线程的优先级(0.0 - 1.0,1.0最高级)
t2.threadPriority = 1;
[t2 start];
(2)、静态创建
[NSThread detachNewThreadSelector:@selector(threadMain0:) toTarget:self withObject:@"111"];
- (void)threadMain0:(NSString *)obj{
NSLog(@"obj = %@",obj); //111
}
③、object:传输给target的唯一参数,也可以为nil。
第一种方式会直接创建线程并且开始运行线程,第二种方式是先创建线程对象,然后再运行线程操作,在运行线程操作前可以设置线程的优先级等线程信息。
[self performSelectorInBackground:@selector(threadMain3:) withObject:@"333”];
NSThread* current = [NSThread currentThread];
+ (NSThread *)currentThread;
+ (BOOL)isMultiThreaded;
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
+ (void)exit;
+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
+ (NSArray *)callStackReturnAddresses;
@property (copy) NSString *name;
@property NSUInteger stackSize;
+ (BOOL)isMainThread NS_AVAILABLE(10_5, 2_0);
+ (NSThread *)mainThread NS_AVAILABLE(10_5, 2_0);
@property (readonly, getter=isExecuting) BOOL executing;
@property (readonly, getter=isFinished) BOOL finished;
@property (readonly, getter=isCancelled) BOOL cancelled;
- (void)cancel NS_AVAILABLE(10_5, 2_0);
- (void)start NS_AVAILABLE(10_5, 2_0);
NSThread* current = [NSThread currentThread];
NSThread* current = [NSThread mainThread];
[NSThread sleepForTimeInterval:2];
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]];
[NSThread sleepUntilDate:date]
注意:线程入口函数一旦调用完成后该线程就结束了。
[self performSelector:@selector(run) onThread:_myThread withObject:nil waitUntilDone:YES];
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
[self performSelector:@selector(run) withObject:nil];
加锁:
解锁:
@synchronized(self)
{
// Everything between the braces is protected by the @synchronized directive.
}
@synchronized,代表这个方法加锁, 相当于不管哪一个线程(例如线程A),运行到这个方法时,都要检查有没有其它线程例如B正在用这个方法,有的话要等正在使用synchronized方法的线程B运行完这个方法后再运行此线程A,没有的话,直接运行。它包括两种用法:synchronized 方法和 synchronized 块。
@synchronized 方法控制对类(一般在IOS中用在单例中)的访问:每个类实例对应一把锁,每个 synchronized 方法都必须获得调用该方法锁方能执行,否则所属就会发生线程阻塞,方法一旦执行,就独占该锁,直到从该方法返回时才将锁释放,此后被阻塞的线程方能获得该锁,重新进入可执行状态。这种机制确保了同一时刻对于每一个类,至多只有一个处于可执行状态,从而有效避免了类成员变量的访问冲突(只要所有可能访问类的方法均被声明为 synchronized)。
synchronized 块:
@通过 synchronized关键字来声明synchronized 块。语法如下:
@synchronized(syncObject) { }
synchronized 块是这样一个代码块,其中的代码必须获得对象 syncObject (如前所述,可以是类实例或类)的锁方能执行,具体机制同前所述。由于可以针对任意代码块,且可任意指定上锁的对象,故灵活性较高。
NSCodition是一种特殊类型的锁,我们可以用它来同步操作执行的顺序。等待某个NSCondition的线程一直被lock,知道其他线程给那个condition发送了信号。
例如:
- (void)run{
while (TRUE) {
// 上锁
[ticketsCondition lock];
[ticketsCondition wait];
//操作
[ticketsCondition unlock];
}
}
//其他线程发送信号通知上面的线程,就可以运行了
-(void)run2{
while (YES) {
[ticketsCondition lock];
[NSThread sleepForTimeInterval:3];
[ticketsCondition signal];
[ticketsCondition unlock];
}
}