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

     
     
  • 相关阅读:
    HDU1879 kruscal 继续畅通工程
    poj1094 拓扑 Sorting It All Out
    (转)搞ACM的你伤不起
    (转)女生应该找一个玩ACM的男生
    poj3259 bellman——ford Wormholes解绝负权问题
    poj2253 最短路 floyd Frogger
    Leetcode 42. Trapping Rain Water
    Leetcode 41. First Missing Positive
    Leetcode 4. Median of Two Sorted Arrays(二分)
    Codeforces:Good Bye 2018(题解)
  • 原文地址:https://www.cnblogs.com/Cheetah-yang/p/4664135.html
Copyright © 2011-2022 走看看