zoukankan      html  css  js  c++  java
  • 多线程Demo1 了解

     
    首先演示一下主线程的阻塞
     
    //  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

     
     
  • 相关阅读:
    Access restriction on class due to restriction on required library rt.jar?
    Why “no projects found to import”?
    MySQL
    您对无法重新创建的表进行了更改或者启用了“阻止保存要求重新创建表的更改”选项
    INTJINTJ——内向+直觉+思维+判
    豆瓣网案例分析报告
    如何使用Git
    如何在不到六个月的时间内成为一个开发者
    关于网站编程Alex
    string
  • 原文地址:https://www.cnblogs.com/Cheetah-yang/p/4664135.html
Copyright © 2011-2022 走看看