zoukankan      html  css  js  c++  java
  • UI进阶之多线程

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
      //[NSThread currentThread] 获取当前的线程
        
        NSLog(@"current == %@", [NSThread currentThread]);
    
        //[NSThread mainThread] 获取主线程
        
        NSLog(@"main == %@", [NSThread mainThread]);
        
      
        //[NSThread isMainThread] 判断当前线程是否是主线程
        NSLog(@"isMainThread == %d", [NSThread isMainThread]);
        
       
        
    #pragma mark --NSObject 开辟子线程--
      
    //    第一个参数: selector 子线程执行的代码
    //    第二个参数: 表示selector传递的参数
        [self performSelectorInBackground:@selector(sayHi) withObject:@"ssss"];
        self.view.backgroundColor = [UIColor redColor];
        
    #pragma  mark -- NSThread手动开辟子线程-
        
        //使用NSThread 开辟子线程
        //参数一: target
        //参数二: action
        //参数三: 传参
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sayHi) object:nil];
        
        //让线程开始执行
        [thread start];
        
        //取消线程  不会真正的取消掉线程, 而是标记 这个被取消了
        [thread cancel];
        
    #pragma  mark -- 使用NSThread自动的去开辟一个线程--
        //使用NSThread自动的开辟一个线程
        //不需要手动开启线程
        [NSThread detachNewThreadSelector:@selector(sayHi) toTarget:self withObject:nil];
       
    }
    
    
    - (void)sayHi
    {
        
    //    //当前线程
    //    NSLog(@"current == %@", [NSThread currentThread]);
    //    
    //    
    //    //主线程
    //    NSLog(@"main == %@", [NSThread mainThread]);
        
        int a = 10000;
        for (int i = 0; i < a; i ++) {
            NSLog( @"i == %d", i);
            
            //关闭线程
            //写在哪里 哪个线程就关闭了, 注意不要随意使用, 使用的时候一定要注意当前线程是否是主线程
            if (i == 500) {
                [NSThread exit];
            }
            
        }
       
       //NSObject 中回到主线程去做某些事情
        //参数一: 回到主线程做的事情
        //参数二: 传递的参数
        //参数三: 直到当前线程已经结束才去做
        [self performSelectorOnMainThread:@selector(onMainThread) withObject:nil waitUntilDone:YES];
        
    }
    
    - (void)onMainThread
    {
        
        self.view.backgroundColor = [UIColor orangeColor];
        
        NSLog(@"main == %@", [NSThread mainThread]);
        
        NSLog(@"current == %@", [NSThread currentThread]);
        
        NSLog(@"ismainThread == %d", [NSThread isMainThread]);
        
    }
  • 相关阅读:
    View转化为bitmap
    Bitmap 与Drawable相互转换
    android studio 连接不到真机
    解决Android sync无法同步问题
    Stetho管理手机
    android sugar no such table
    android 建数据库的正确写法
    android JSON 数据解析
    android notification 理解
    android aidl 简单使用
  • 原文地址:https://www.cnblogs.com/huyibo/p/5370351.html
Copyright © 2011-2022 走看看