iOS 多线程编程<一、多线程实现方式>

来源:互联网 发布:大数据金融的风险 编辑:程序博客网 时间:2024/05/01 16:40


一:多线程实现方式


二:具体实现方式

(1)pthread实现方式
////  ViewController.m//  Thread////  Created by fe on 16/9/26.//  Copyright © 2016年 fe. All rights reserved.//#import "ViewController.h"#import <pthread.h>@interface ViewController ()@end@implementation ViewController- (IBAction)btnClick:(UIButton *)sender {    //打印当前线程    NSLog(@"------%@",[NSThread currentThread]);    //创建线程    pthread_t thread;    /*     第一个参数:线程对象     第二个参数:线程属性     第三个参数:void * _Nullable (* _Nonnull)(void * _Nullable)指向函数的指针     第四个参数:函数的参数     */    pthread_create(&thread, NULL, run, NULL);}void *run(void *param){    NSLog(@"------%@",[NSThread currentThread]);    return NULL;}@end
(2)nsthread实现方式

<span style="font-size:14px;">////  ViewController.m//  Thread////  Created by fe on 16/9/26.//  Copyright © 2016年 fe. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (IBAction)btnClick:(UIButton *)sender {    [self creatThread5];    }//第一种创建线程方式- (void)creatThread1{    NSThread *thread = [[NSThread alloc] initWithBlock:^{        NSLog(@"-----%@",[NSThread currentThread]);    }];    thread.name = @"block线程";    thread.threadPriority = 1.0;    [thread start];}//第二种创建线程方式- (void)creatThread2{    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"ios多线程"];    thread.name = @"第二种创建线程方式";    thread.threadPriority = 1.0;    [thread start];}//第三种创建线程方式- (void)creatThread3{    [NSThread detachNewThreadWithBlock:^{        NSLog(@"------%@",[NSThread currentThread]);    }];}//第四种创建线程方式- (void)creatThread4{    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"第四种创建线程方式"];}//第五种创建线程方式- (void)creatThread5{    //[self performSelectorInBackground:@selector(go) withObject:nil];    [self performSelector:@selector(go) withObject:nil afterDelay:2.0];}-(void)run:(NSString *)str{        NSLog(@"%@-----%@",str,[NSThread currentThread]);    }-(void)go{    NSLog(@"-----%@",[NSThread currentThread]);}@end</span><span style="font-size: 24px;"></span>


0 0
原创粉丝点击