/*-(void)running:(id)sender
{
while(1)
{
//让线程休眠2秒
[NSThread sleepForTimeInterval:2];
NSLog(@"线程的名字:%@",[[NSThread currentThread] name]);
}
}*/
- (IBAction)threadTap:(id)sender
{
[NSThread currentThread].name=@"主线程";
//用类的行为自动启动线程
//[NSThread detachNewThreadSelector:@selector(running:) toTarget:self withObject:nil];
//这种方法创建的线程必需手动启动
NSThread *t=[[NSThread alloc]initWithTarget:self selector:@selector(running:) object:nil];
[t setName:@"我的线程"];
//启动线程
[t start];
while(1)
{
NSLog(@"线程的名字:%@",[[NSThread currentThread] name]);
}
}
- (IBAction)operationTap:(id)sender
{
NSInvocationOperation * nio=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(running:) object:@"me"];
NSOperationQueue *queue=[[NSOperationQueue alloc]init];
[queue addOperation:nio];
//[nio start];
}
-(void)running:(id)_obj
{
while(1)
{
//让线程休眠2秒
[NSThread sleepForTimeInterval:2];
NSLog(@"线程的名字:%@",_obj);
}
}
- (IBAction)gcdTap:(id)sender
{
//block 块 函数
//返回值 (^块的名字)(参数列表)=(^实际的参数列表){
//块的主题
//}
//返回值 函数名字(参数列表)c语言的函数的定义形式
//{
//}
//定义一个块
//定义一个可以被块操作的(块外边的)变量,
// __block int num ;
// void (^myblock)(void)=^{
// NSLog(@"%d",num--);
// };
/*int (^sum)(int)=^(int n){
int s=0;
for(int i=1;i<101;i++)
{
s+=i;
}
return s;
};
int s=sum(100);
NSLog(@"%d",s);
//块的调用,括号为空,表示无参调用
myblock();*/
//NSThread
//NSOperation
//gcd线程
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"this gcd1 thread");
//启动主线程中的函数
[self performSelectorOnMainThread:@selector(mainn:) withObject:@"222" waitUntilDone:YES];
dispatch_async(dispatch_get_main_queue(), ^{
//访问界面上的按钮
UIButton *button=(UIButton *)[self.view viewWithTag:10];
//设定界面按钮的文本
[button setTitle:@"Hello" forState:UIControlStateNormal];
});
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
while (1)
{
NSLog(@"this gcd2 thread");
}
});
while (1)
{
NSLog(@"this main thread");
}
}
-(void)mainn:(id)sender
{
//访问界面上的按钮
UIButton *button=(UIButton *)[self.view viewWithTag:10];
//设定界面按钮的文本
[button setTitle:@"Hello" forState:UIControlStateNormal];
}
浙公网安备 33010602011771号