• 网络开始---多线程---NSThread-01-基本使用(了解)(二)


     1 #import "HMViewController.h"
     2 
     3 @interface HMViewController ()
     4 
     5 @end
     6 
     7 @implementation HMViewController
     8 
     9 - (void)viewDidLoad
    10 {
    11     [super viewDidLoad];
    12     // Do any additional setup after loading the view, typically from a nib.
    13 }
    14 
    15 //下载操作,
    16 - (void)download:(NSString *)url
    17 {
    18     NSLog(@"下载东西---%@---%@", url, [NSThread currentThread]);
    19     
    20     
    21     
    22     
    23     
    24 }
    25 
    26 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    27 {
    28     [self createThread3];
    29 }
    30 
    31 /**
    32  * 创建线程的方式3
    33  隐式创建线程并自动启动线程
    34  */
    35 - (void)createThread3
    36 {
    37 //    这2个不会创建线程,在当前线程中执行
    38 //    [self performSelector:@selector(download:) withObject:@"http://c.gif"];
    39 //    [self download:@"http://c.gif"];
    40     
    41     //这个隐式创建线程,在后台会自动创建一条子线程并执行download方法,
    42     [self performSelectorInBackground:@selector(download:) withObject:@"http://c.gif"];
    43 }
    44 
    45 /**
    46  * 创建线程的方式2
    47  创建线程后自动启动线程
    48  */
    49 - (void)createThread2
    50 {
    51     //从当前线程中分离出一条新的线程
    52     [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"http://a.jpg"];
    53 }
    54 
    55 /**
    56  * 创建线程的方式1
    57  创建线程后不会自动启动,需要写一句启动才会启动线程
    58  这种创建线程的方法是3种当中最好的,可以对线程进行详细的设置
    59  
    60  */
    61 - (void)createThread1
    62 {
    63     // 创建线程
    64     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"http://b.png"];
    65     
    66     //线程的名字,打印线程的时候可以看到打印的线程的名字
    67     thread.name = @"下载线程";
    68     
    69     object://你开辟线程要执行的方法要传的参数,比如这里传一个url,传到download方法里
    70     //这个参数是要从当前线程传到子线程中去的
    71     
    72     // 启动线程(调用self的download方法) 只有启动线程才会调用self的download方法
    73     [thread start];  //必须有这一句才能启动线程
    74     //并且执行过程是在子线程中执行的,就是新开辟的一条线程 把耗时操作成功放到子线程中去
    75     
    76     [NSThread mainThread];//获得主线程
    77    NSThread *current=[NSThread currentThread];//获得当前线程
    78     
    79     
    80     [thread isMainThread];//判断当前线程(新创建线程)是否为主线程,返回Bool值
    81     [NSThread isMainThread];// 判断当前执行代码的方法是否在主线程,返回Bool值
    82     
    83 }
    84 
    85 @end
  • 相关阅读:
    [DOJ练习] 无向图的邻接矩阵表示法验证程序
    [DOJ练习] 求无向图中某顶点的度
    [邻接表形式]有向图的建立与深度,广度遍历
    [DOJ练习] 有向图的邻接表表示法验证程序(两种写法)
    [Java 学习笔记] 异常处理
    [总结]单源最短路(朴素Dijkstra)与最小生成树(Prim,Kruskal)
    时间选择插件jquery.timepickr
    页面值传入后台出现中文乱码
    CheckTreecheckbox树形控件
    JQuery EasyUI DataGrid
  • 原文地址:https://www.cnblogs.com/ithongjie/p/4818081.html
Copyright © 2020-2023  润新知