LHF Objective-C语法(12)多线程

来源:互联网 发布:python twisted 过时 编辑:程序博客网 时间:2024/05/16 09:21

1、NSThread

  (1)创建线程对象的方法:

        a、-(id) init;

        b、-(id) initWithTarget:(id) target selector:(SEL) selector object:(id) argument;

        c、+(void) detachNewThreadSelector:(SEL) aSelector toTarget:(id) aTarget withObject:(id) anArgument  //使用这个类方法,不用release(因为没有使用alloc)

        启动一个线程用star,结束一个线程用exit(使用exit时,首先要将这个线程的引用计数归0)

  (2)NSCondition 执行同步操作,相当于java的lock

  (3)@synchronized(要加锁的对象){

                    //同步执行的代码

             }

例1:

//SellTickets.h=========================#import <Foundation/Foundation.h>@interface SellTickets : NSObject{int tickets;//未售出的票数int count;//售出的票数NSThread *ticketsThread1;//线程1NSThread *ticketsThread2;//线程2NSThread *ticketsThread3;//线程3NSCondition *ticketsCondition;//同步锁}-(void) ticket;//售票方法@end

#import "SellTickets.h"@implementation SellTickets-(void) ticket{tickets = 100;count = 0;ticketsCondition = [[NSCondition alloc] init];    ticketsThread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];    [ticketsThread1 setName:@"Thread-1"];    [ticketsThread1 start];    ticketsThread2 = [[NSThread alloc] initWithTarget:self                                             selector:@selector(run) object:nil];[ticketsThread2 setName:@"Thread-2"];[ticketsThread2 start];    ticketsThread3 = [[NSThread alloc] initWithTarget:self                                             selector:@selector(asyn) object:nil];[ticketsThread3 setName:@"Thread-3"];[ticketsThread3 start];    [NSThread sleepForTimeInterval:80];//让主线程暂停80秒}//线程之间是否异步执行//按照asyn中的代码,在程序5秒后,线程3会夹杂在线程1、2的售票输出语句中输出-(void)asyn{[NSThread sleepForTimeInterval:5];NSLog(@"*******************************");}-(void)run{while(YES){//上锁[ticketsCondition lock];if(tickets >0){[NSThread sleepForTimeInterval:0.5];count = 100 - tickets;NSLog(@"当前票数%d,售出%d,线程名%@",tickets,count,                  [[NSThread currentThread] name]);tickets--;}else{break;}//解锁[ticketsCondition unlock];    }}    -(void)dealloc{        //回收线程,同步锁的实例        [ticketsThread1 release];        [ticketsThread2 release];        [ticketsThread3 release];        [ticketsCondition release];        [super dealloc];    }    @end
#import <Foundation/Foundation.h>#import "SellTickets.h"int main (int argc, const char * argv[]){    SellTickets *st = [[SellTickets alloc] init];    [st ticket];    [st release];    return 0;}  

  (4)与主线程交互

如果想更新UI上的某一个部件,就需要在发起的新线程里调用UI所在的主线程上的一个方法,新线程不能直接访问主线程的方法,需要在润方法中使用如下方法

[self performSelectorOnMainThread:@selector(moveText) withObject:nil waitUntilDone:NO];

  (3)线程池



原创粉丝点击