IOS多线程-NSThread

2015-07-08  本文已影响553人  静之先生

NSThread

    //创建线程
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector() object:nil];
    //object存的是参数

    //修改参数名
    thread.name = @"我的多线程";

    //获取主线程
    NSThread *thread = [NSThread mainThread];

    //创建线程并自动启动
    [NSThread detachNewThreadSelector:@selector() toTarget:self withObject:nil];

    //隐士创建
    [self performSelectorInBackground:@selector() withObject:nil];

    //获取当前线程
    [NSThread currentThread]

    //启动线程
    - (void)start;


    //阻塞(暂停)线程
    + (void)sleepUntilDate:(NSDate *)date;
    + (void)sleepForTimeInterval:(NSTimeInterval)ti;
    // 进入阻塞状态

    //停止当前正在运行的进程
    + (void)exit;
    // 进入死亡状态,一旦死亡则不能重启

资源共享

解决办法互斥锁

#import "ViewController.h"

@interface ViewController ()
/** 售票机1*/
@property (strong,nonatomic) NSThread *threadOne;
/** 售票机2*/
@property (strong,nonatomic) NSThread *threadTwo;
/** 售票机3*/
@property (strong,nonatomic) NSThread *threadThree;
/** 售票机4*/
@property (strong,nonatomic) NSThread *threadFour;
/** 售票机5*/
@property (strong,nonatomic) NSThread *threadFive;

/** 数量*/
@property (assign,nonatomic) NSInteger count;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建线程
    self.threadOne = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"one"];
    self.threadTwo = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"two"];
    self.threadThree = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"three"];
    self.threadFour = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"four"];
    self.threadFive = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"five"];
    self.count = 100;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //开始线程
    [self.threadOne start];
    [self.threadTwo start];
    [self.threadThree start];
    [self.threadFour start];
    [self.threadFive start];
}


- (void)run:(NSString *)param
{
    while (1) {
        //self是锁对象
        @synchronized(self)
        {

            if (self.count > 0) {
                _count--;
                NSLog(@"%zd-----%@",self.count,[NSThread currentThread]);
            }
            else
            {
                NSLog(@"卖完了----%@",[NSThread currentThread]);
                break;
            }
        }
    }
}
@end

下载网络数据

 NSURL *url = [NSURL URLWithString:@"url"];
 NSDate *begin = [NSDate date];
 NSData *data = [NSData dataWithContentsOfURL:url];
上一篇 下一篇

猜你喜欢

热点阅读