zoukankan      html  css  js  c++  java
  • 网络开始---多线程---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
  • 相关阅读:
    FFT学习及简单应用(一点点详细)
    Codeforces 1131 (div 2)
    【NOI2012】魔幻棋盘
    【hdu多校联考第二场】Odd Shops
    【Helvetic Coding Contest 2018】B2. Maximum Control (medium)
    解线性同余方程组
    Math teacher's homework
    【NOIP模拟赛】一道挖掉背景的数学题
    逆向基础-模块隐藏之断链
    解决请求筛选模块被配置为拒绝包含的查询字符串过长的请求
  • 原文地址:https://www.cnblogs.com/ithongjie/p/4818081.html
Copyright © 2011-2022 走看看