线程:
{
NSInteger _count;
//锁
NSLock *_lock;
}
_lock=[[NSLock alloc] init]; //在didload里边初始化_lock
第一种:
NSThread *thred1=[[NSThread alloc]initWithTarget:self selector:@selector(sum) object:nil];
//给你的线程起个名字
thred1.name=@"thred1";
//启动线程
[thred1 start];
//关闭线程
[thred1 cancel];
第二种(不需要手动开启的)
[NSThread detachNewThreadSelector:@selector(sum) toTarget:self withObject:nil];第三种继承与NSObject方式
[self performSelectorInBackground:@selector(sum) withObject:nil];线程里边执行的方法
//要在线程中执行的方法
-(void)sum{
long long sum=0;
for (long long i=0; i<635500000; i++) {
NSLog(@"线程:%@ %lld",[NSThread currentThread],sum+=i);
}
NSLog(@"结束了");
}
简单售票多线程
//票数
_count=20;
//线程
NSThread *thred11=[[NSThread alloc] initWithTarget:self selector:@selector(saleticket) object:nil];
thred11.name=@"售票1";
[thred11 start];
NSThread *thred22=[[NSThread alloc] initWithTarget:self selector:@selector(saleticket) object:nil];
thred22.name=@"售票2";
[thred22 start];
执行方法
//卖票的方法
-(void)saleticket{
while (YES) {
[_lock lock];
if (_count > 0) {
NSLog(@"%@ : 当前票数 %d", [NSThread currentThread],_count--);
//延迟
sleep(1);
[_lock unlock];
}else{
NSLog(@"票以售完");
break;
}
}
}
NSOperation
有两个子类 NSInvocationOperation NSBlockOperation .
NSOperationQueue 是操作队列,他用来管理一组Operation对象的执行,会根据需要自动为Operation开辟合适数量的线程,以完成任务的并行执行.
// NSOperation
NSInvocationOperation *inOP=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocation) object:nil];
// [inOP start];
//
NSBlockOperation *blOp=[NSBlockOperation blockOperationWithBlock:^{
NSLog(@"我是Block");
}];
//创建队列
NSOperationQueue *queue=[[NSOperationQueue alloc] init];
//设置最大同时执行数量
queue.maxConcurrentOperationCount=3;
//添加事件(先进先出)
[queue addOperation:inOP];
[queue addOperation:blOp];
方法
-(void)invocation{
// NSLog(@"%@",[NSThread currentThread]);
NSLog(@"我是方法");
}
10万+

被折叠的 条评论
为什么被折叠?



