- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//获取当前线程
NSThread *current = [NSThread currentThread];
NSLog(@"当前线程为 %@",current);
//初始化线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
//设置线程的优先级(0.0-1.0)
thread.threadPriority = 1.0;
thread.name = @"新线程1";
[thread start];
}
- (void)run
{
NSLog(@"线程执行");
//获取当前线程
NSThread *current = [NSThread currentThread];
NSLog(@"当前线程为 %@",current);
//线程休眠,可以模拟耗时操作
[NSThread sleepForTimeInterval:2];
//获取主线程
NSThread *mainThread = [NSThread mainThread];
NSLog(@"子线程中获得主线程 %@",mainThread);
}
//后台创建一个线程来执行任务,需要在调用的方法中使用自动释放池 [self performSelectorInBackground:@selector(run3) withObject:nil];
- (void)run3
{
@autoreleasepool {
NSLog(@"主线程3:%@,当前线程3:%@",[NSThread mainThread],[NSThread currentThread]);
}
}
//测试在子线程中调用主线程更新UI
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSThread *subThread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
//NSThread可以控制线程开始
[subThread start];
}
- (void)run
{
NSLog(@"主线程1:%@,当前线程1:%@",[NSThread mainThread],[NSThread currentThread]);
//以下方法需要在子线程中调用
[self performSelectorOnMainThread:@selector(invocationMainThread) withObject:nil waitUntilDone:YES];
}
- (void)invocationMainThread
{
NSLog(@"主线程2:%@,当前线程2:%@",[NSThread mainThread],[NSThread currentThread]);
NSLog(@"调用主线程更新UI");
}
@implementation MyThread
- (void)main
{
NSLog(@"main方法执行");
}
@end
//可以自己写一个子类,继承自NSThread,需要重写main方法
/**
* 执行的代码是在main中的,而不是使用@selector.
使用main方法,线程中执行的方法是属于对象本身的,这样可以在任何其他需要使用这个线程方法的地方使用,而不用再一次实现某个方法。
而其他的直接NSThread的创建线程,线程内执行的方法都是在当前的类文件里面的。
*/
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
MyThread *thread = [[MyThread alloc] init];
[thread start];
}
//线程休眠,可以模拟耗时操作 [NSThread sleepForTimeInterval:2];
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有