1 #import "ViewController.h" 2 3 @interface ViewController () 4 5 @end 6 7 @implementation ViewController 8 9 - (void)viewDidLoad { 10 [super viewDidLoad]; 11 // Do any additional setup after loading the view, typically from a nib. 12 //第一种方式 13 UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeSystem]; 14 btn1.frame = CGRectMake(50, 100, 100, 40); 15 [btn1 setTitle:@"按钮一" forState:UIControlStateNormal]; 16 [btn1 addTarget:self action:@selector(threadOne:) forControlEvents:UIControlEventTouchUpInside]; 17 [self.view addSubview:btn1]; 18 19 //第二种方式 20 UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeSystem]; 21 btn2.frame = CGRectMake(50, 200, 100, 40); 22 [btn2 setTitle:@"按钮二" forState:UIControlStateNormal]; 23 [btn2 addTarget:self action:@selector(threadTwo:) forControlEvents:UIControlEventTouchUpInside]; 24 [self.view addSubview:btn2]; 25 } 26 27 //第二种方式 28 -(void)threadTwo:(id)sender 29 { 30 //NSLog(@"点击了按钮"); 31 //参数一:线程执行体方法所属的对象 32 //参数二:线程执行体对应的方法 33 //参数三:线程执行体方法的实参 34 NSNumber *n=@50; 35 //创建线程 并没有启动(需手动启动) 36 NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(createThreadTwo:) object:n]; 37 t.name = @"线程B"; 38 [t start]; 39 40 } 41 42 -(void)createThreadTwo:(NSNumber *)n 43 { 44 for (int i=0; i<n.intValue; i++) { 45 NSThread *t = [NSThread currentThread]; 46 NSLog(@"执行了%@:%d",t.name,i); 47 } 48 } 49 50 //第一种方式 51 -(void)threadOne:(id)sender 52 { 53 //参数一:线程执行体的方法 54 //参数二:线程执行体所属对象 55 //参数三:线程执行体方法传递的实参 56 NSNumber *n = @100; 57 //创建并启动一个线程 58 [NSThread detachNewThreadSelector:@selector(createOne:) toTarget:self withObject:n]; 59 } 60 61 - (void)createOne:(NSNumber *)n 62 { 63 [NSThread currentThread].name = @"线程A"; 64 65 for (int i=0; i<n.intValue; i++) { 66 //[NSThread sleepForTimeInterval:1]; 67 NSLog(@"执行%@:%d",[NSThread currentThread].name,i); 68 } 69 } 70 71 - (void)didReceiveMemoryWarning { 72 [super didReceiveMemoryWarning]; 73 // Dispose of any resources that can be recreated. 74 } 75 76 @end