线程同步的两种防护四

来源:互联网 发布:小猪cms微店系统源码 编辑:程序博客网 时间:2024/04/25 11:44

#import "TRViewController.h"


@interface TRViewController ()

@property (nonatomic)int ticketsCount;

@property (nonatomic)int selledCount;

@property (nonatomic, strong)NSLock *mylock;

@end


@implementation TRViewController


- (void)viewDidLoad

{

    [superviewDidLoad];

self.ticketsCount =100;

    self.mylock = [[NSLockalloc]init];

    

    NSThread *t1 = [[NSThreadalloc]initWithTarget:selfselector:@selector(beginSell) object:Nil];

    t1.name = @"一号窗口";

    [t1 start];

    NSThread *t2 = [[NSThreadalloc]initWithTarget:selfselector:@selector(beginSell) object:Nil];

    t2.name = @"二号窗口";

    [t2 start];

}


-(void)beginSell{

    while (YES) {

        

        //同步代码块任意对象都有一个锁的标示(锁旗标)

//        2

        @synchronized(self)

        {

    

       // [self.mylock lock];

            NSString *name = [NSThreadcurrentThread].name;

            NSLog(@"%@开始卖票",name);

            [NSThreadsleepForTimeInterval:1];

            self.selledCount++;

            NSLog(@"%@卖票结束卖了%d号票还剩%d",name,self.selledCount,self.ticketsCount-self.selledCount);

        }

       // [self.mylock unlock];

    }

}

0 0
原创粉丝点击