//
// ViewController.m
// 10 NSThread
//
// Created by Tracy on 15/5/29.
// Copyright (c) 2015年 Tracy. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIProgressView *progressView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// [self doWork];
// [self doWork];
// [self doWork];
}
- (IBAction)useThread:(UIButton *)sender
{
NSThread*thread=[[NSThread alloc]initWithTarget:self selector:@selector(doWork) object:nil];
[thread start];//启动线程
//第二种方式
[NSThread detachNewThreadSelector:@selector(doWork) toTarget:self withObject:nil];
//第三种方式
[self performSelectorInBackground:@selector(doWork) withObject:nil];
}
- (IBAction)updateProgress:(UIButton *)sender
{
[NSThread detachNewThreadSelector:@selector(updateProgressView) toTarget:self withObject:nil];
}
-(void)updateProgressView
{
self.progressView.progress=0.0f;
for (int i=0; i<100; i++) {
[NSThread sleepForTimeInterval:0.1f];
[self performSelectorOnMainThread:@selector(upDateUI) withObject:nil waitUntilDone:YES];
}
}
-(void)upDateUI
{
self.progressView.progress+=0.01;
}
-(void)doWork
{
for (int i=0; i<30; i++) {
[NSThread sleepForTimeInterval:0.01f];
NSLog(@"%d thread %@",i,[NSThread currentThread]);
}
}
- (IBAction)fetchMoney:(UIButton *)sender
{
NSThread*husband=[[NSThread alloc]initWithTarget:self selector:@selector(fetchMoneyByWho:) object:@"husband"];
[husband start];
NSThread*wife=[[NSThread alloc]initWithTarget:self selector:@selector(fetchMoneyByWho:) object:@"wife"];
[wife start];
NSThread*dau=[[NSThread alloc]initWithTarget:self selector:@selector(fetchMoneyByWho:) object:@"dau"];
[dau start];
}
-(void)fetchMoneyByWho:(NSString*)name
{
static int money=10000;
// NSLog(@"before who %@,how much %d",name,money);
//
// money-=2000;
// NSLog(@"after who %@,how much %d",name,money);
//@synchronized 可以使线程同步,避免异步使取钱,买票等情况发生错误
@synchronized (self)
{
NSLog(@"before who %@,how much %d",name,money);
money-=2000;
NSLog(@"after who %@,how much %d",name,money);
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end