我在AppDelegate.m里写的代码。连续介绍几个创建线程的方法。
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
self.window.rootViewController = [[UIViewController alloc]init];
// 第一种
//NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(mutableThread:) object:nil];
//[thread start];
//第二种方法
//[NSThread detachNewThreadSelector:@selector(mutableThread:) toTarget:self withObject:nil];
//3方法
//[self performSelectorInBackground:@selector(mutableThread:) withObject:nil];
//4种方法
// NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
//[operationQueue addOperationWithBlock:^{
//for (int i = 0; i<100; i++) {
// NSLog(@"主线程",i);
// }
//}];
//5中方法
//创建一个线程队列
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//设置线程执行的并发数//设置并发数为1后,那线程2最后执行
operationQueue.maxConcurrentOperationCount = 1;
//创建一个线程操作对象
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread:) object:nil];
//创建一个线程操作对象
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread2:) object:nil];
//设置线程的优先级
operation2.queuePriority = NSOperationQueuePriorityHigh;
//将线程添加到线程队列中
[operationQueue addOperation:operation];
[operationQueue addOperation:operation2];
return YES;
}
- (void)mutableThread:(NSString *)t
{
for (int i=0; i<100; i++) {
NSLog(@"--%d多线程",i);
}
//跳到主线程执行
[self performSelectorOnMainThread:@selector(mainThread) withObject:nil waitUntilDone:YES];
}
- (void)mutableThread2:(NSString *)t
{
for (int i=0; i<100; i++) {
NSLog(@"---%d多线程2",i);
}
}
- (void)mainThread
{
BOOL isMain = [NSThread isMainThread];
if (isMain) {
NSLog(@"1111111111111111111mainThread");
}
}
@end