zoukankan      html  css  js  c++  java
  • iOS多线程开发小demo

    首先演示一下主线程的阻塞

    //  DYFViewController.m
    //  623-01-阻塞多线程
    //
    //  Created by dyf on 14-6-23.
    //  Copyright (c) 2014年 ___FULLUSERNAME___. All rights reserved.
    //
    
    #import "DYFViewController.h"
    
    @interface DYFViewController ()
    
    @end
    
    @implementation DYFViewController
    - (IBAction)btnOnClick {
        // 1.获取当前的线程
        NSThread *thread = [NSThread currentThread];
        
        // 2.打印线程
        NSLog(@"%@", thread);
        
        // 3.执行一线耗时的操作
        for (int i = 0; i < 9999; i++) {
            NSLog(@"%@", thread);
            // 此时点击按钮,在执行完耗时操作之前,按钮一直是高亮状态,期间用户点击其他的UI控件也不好响应
        }
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    	// Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
    

     容易发现,在耗时操作期间,其它UI操作都被延时了,造成用户的卡顿现象

    --------创建子线程方法1--pthread

    //  DYFViewController.m
    //  623-02-pthread
    //
    //  Created by dyf on 14-6-23.
    //  Copyright (c) 2014年 ___FULLUSERNAME___. All rights reserved.
    //
    
    #import "DYFViewController.h"
    #import <pthread.h>
    
    @interface DYFViewController ()
    
    @end
    
    @implementation DYFViewController
    
    // c语言函数
    void *run(void *data)
    {
        // 1.获取当前的线程
        NSThread *cThread = [NSThread currentThread];
        
        // 2.打印线程
        NSLog(@"%@", cThread);
        
        // 3.h耗时操作
        for (int i = 0; i < 9999; i++) {
            NSLog(@"%@", cThread);
        }
    
        return NULL;
    }
    
    - (IBAction)btnOnClick {
        // 1.获取当前的线程
        NSThread *thread = [NSThread currentThread];
        
        // 2.打印线程
        NSLog(@"%@", thread);
        
        // 3.执行一线耗时的操作 : 创建一套子线程
        
        pthread_t threadId;
        pthread_create(&threadId, NULL, *run, NULL);
       
    }
    
    
    @end
    

     小结:此方法不常用,了解即可

  • 相关阅读:
    序列终结者
    CF696C PLEASE
    [清华集训]Rmq Problem / mex
    CF786B Legacy
    链表结构详解
    synchronized同步方法和同步代码块的区别
    关于守护线程定义
    线程的优先级
    mysql查询当天的数据
    java以正确的方式停止线程
  • 原文地址:https://www.cnblogs.com/dyf520/p/3805302.html
Copyright © 2011-2022 走看看