NSThread三种方式创建子线程
/** * NSThread创建线程方式1 * 1> 先创建初始化线程 * 2> start开启线程 */ -(void)creatNSThread { NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"线程A"]; //为线程设置一个名称 thread.name=@"线程A"; //开启线程 [thread start]; NSThread *thread2=[[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"线程B"]; //为线程设置一个名称 thread2.name=@"线程B"; //开启线程 [thread2 start]; } /** * NSThread创建线程方式2 *创建完线程直接(自动)启动 */ -(void)creatNSThread2 { // NSThread *thread=[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"创建完线程直接(自动)启动"]; [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"创建完线程直接(自动)启动"]; } /** * NSThread创建线程方式3 * 隐式创建线程, 并且直接(自动)启动 */ -(void)creatNSThread3 { //在后台线程中执行===在子线程中执行 [self performSelectorInBackground:@selector(run:) withObject:@"隐式创建"]; } -(void)run:(NSString *)str { //获取当前线程 NSThread *current=[NSThread currentThread]; //打印输出 for (int i=0; i<100; i++) { NSLog(@"run---%@---%@%i",current,str,i); } }
时间: 2024-10-10 05:32:29