10.1 NSThread 不常用 难以管理
来源:互联网 发布:淘宝店铺宣传广告语 编辑:程序博客网 时间:2024/06/05 19:42
//// 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
0 0
- 10.1 NSThread 不常用 难以管理
- 为何编程难以管理?
- 数字化管理难以掩盖的教学魅力
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- NSThread
- RTP协议分析
- WinCE串口编程API函数
- js发送邮件确定email地址
- sublime package control install
- 大数据时代,你还为数据单位,而困惑么? 计算机存储单位:Byte、KB、MB、GB、TB、PB、EB分别叫什么?他们的进率是多少?
- 10.1 NSThread 不常用 难以管理
- jaxb
- android button测试
- java之Integer知识整理
- 5,29 微积分 直线与曲线交面积
- jquery 中json数组的操作 增删改
- TP 配置项及说明
- 如何提高SAT文章阅读速度?
- Android WebView先加载网页文字,后加载图片