用NSThread创建多线程(掌握)

Posted on 2016-07-16 17:30  柠檬片  阅读(113)  评论(0)    收藏  举报
 1 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     [self createThread3];
 4     
 5 }
 6 
 7 /*
 8  第三种创建线程的方式
 9  特点:默认开启线程
10  */
11 -(void)createThread3
12 {
13 
14     [self performSelectorInBackground:@selector(run:) withObject:@"后台线程"];
15 }
16 
17 /*
18  第二种创建线程的方式
19  特点:默认开启线程
20  */
21 -(void)createThread2
22 {
23     /*
24      第一个参数:选择器,调用哪个方法
25      第二个参数:目标对象
26      第三个参数:前面方法需要传递的参数
27      */
28     [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"wendingding"];
29 
30 }
31 /*
32  第一种创建线程的方式
33  特点:需要调用start方法开启线程
34  */
35 -(void)createThread1
36 {
37     //    NSLog(@"%@",[NSThread currentThread]);
38     //创建线程
39     /*
40      第一个参数:目标对象
41      第二个参数:选择器,调用哪个方法
42      第三个参数:前面方法需要传递的参数
43      */
44     //    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
45     //    //设置基本属性
46     //    thread1.name = @"线程1";
47     //
48     //    //线程优先级
49     //    [thread1 setThreadPriority:1.0];
50     //
51     //    //开启线程
52     //    [thread1 start];
53     //
54     //    NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
55     //        thread2.name = @"线程2";
56     //    [thread2 setThreadPriority:0.1];
57     //    //开启线程
58     //    [thread2 start];
59     
60     XMGThread *thread3 = [[XMGThread alloc]initWithTarget:self selector:@selector(run) object:nil];
61     thread3.name = @"线程3";
62     
63     //开启线程
64     [thread3 start];
65 }
66 -(void)run:(NSString *)str
67 {
68 
69     for (NSInteger i = 0; i<1000; i++) {
70             NSLog(@"-%zd--run---%@--%@",i,[NSThread currentThread],str);
71     }
72 }
用NSThread创建多线程