//
// SellTicketViewController.m
// multi-thread
//
// Created by lanouhn on 16/3/2.
// Copyright © 2016年 sq. All rights reserved.
//
#import "SellTicketViewController.h"
@interface SellTicketViewController ()
/** 票的总数 */
@property(nonatomic, assign)NSInteger count;
@end
@implementation SellTicketViewController
// 模拟3个窗口卖票,其实就是3个线程
// 线程数据错乱, 线程安全问题 - 就要加锁 多对象处理同一个数据
- (IBAction)sellTicket:(id)sender {
// 创建一把锁
NSLock *lock = [[NSLock alloc]init];
for (int i = 0; i < 3; i++) {
// 我们加的锁属于互斥锁 , 同一把锁self
// 对数据的操作,对线程而言,互斥的,只能有一个线程执行,其他两个等待
// 1. @synchronized
// 2. NSlock
// 系统方法
// 在子线程中操作的代码
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[lock lock];
// @synchronized(self) {
while (self.count > 0) {
NSLog(@"count = %ld",self.count);
self.count--;
}
// }
[lock unlock];
});
}
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.count = 100;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
12306线程管理
最新推荐文章于 2022-06-09 21:18:00 发布