iOS多线程初见

 . 三种创建线程的方法

 //第一种

      NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(doAction) object:nil];

     //线程名

     thread1.name = @"thread1";

     //线程优先级,0 ~ 1

     thread1.threadPriority = 1.0;

     //开启线程

     [thread1 start];

 //第二种

     //通过类方法创建线程,不用显示的开启start

     [NSThread detachNewThreadSelector:@selector(doAction) toTarget:self withObject:nil];

 //第三种

     //隐式创建多线程

     [self performSelectorInBackground:@selector(doAction:) withObject:nil];

 @implementation ViewController

 - (void)viewDidLoad {

     [super viewDidLoad];

     // Do any additional setup after loading the view, typically from a nib.

     NSLog(@"mainThread - %@",[NSThread mainThread]);

     NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(handleAction) object:nil];

     //就绪状态

     [thread start];

 }

 - (void)handleAction {

     for (NSInteger i =  ; i < ; i ++) {

         //阻塞状态

 //        [NSThread sleepForTimeInterval:2];

 //        [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];

 //        NSLog(@"%@,%@",[NSThread currentThread],@(i));

         //可以在子线程获取主线程

         NSLog(@"mainThread - %@",[NSThread mainThread]);    

         if (i == ) {

             //退出

             [NSThread exit];

         } 

     }

 }

 .同步代码块实现买票功能

 @implementation ViewController

 - (void)viewDidLoad {

     [super viewDidLoad];

     // Do any additional setup after loading the view, typically from a nib.

     self.tickets = ;

     NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];

 //    thread1.name = @"computer";

     [thread1 start];

     NSThread * thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];

 //    thread2.name = @"phone";

     [thread2 start];

 }

 - (void)saleTicket {

     while () {

 //        [NSThread sleepForTimeInterval:1];

         //token必须所有线程都能访问到,一般用self

 //        @synchronized() {

             //代码段

 //        }

 //        NSObject * o = [[NSObject alloc] init];

         //互斥锁

         @synchronized(self) {

             [NSThread sleepForTimeInterval:];

             if (self.tickets > ) {

                 NSLog(@"%@ 还有余票 %@ 张",[NSThread currentThread],@(self.tickets));

                 self.tickets -- ;

             } else {

                 NSLog(@"票卖完了");

                 break;

             }

         }

     }

 }
上一篇:Oracle创建用户并给用户授权查询指定表或视图的权限


下一篇:oracle 创建表、删除表、添加字段、删除字段、表备注、字段备注、修改表属性