下面这个东西干了这么个事情:分出两个Thread,都执行对value值+1,并打印的操作。
吐槽:笔者写似乎是个线程不安全的典型,请勿参考。
//
// ViewController.m
// MTTest
//
// Created by 鲁辰 on 7/29/15.
// Copyright (c) 2015 ChenLu. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, assign) NSUInteger value;
@end
@implementation ViewController
@synthesize value;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//NSThread
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(run)
object:nil];
[myThread start];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)run {
while (YES) {
@synchronized(self) {
value++;
}
NSThread *current = [NSThread currentThread];
NSLog(@"Value: %lu, Thread: %@", (unsigned long)value, current);
sleep(1);
}
}
@end
代码链接:https://gist.github.com/1992chenlu/41b3adfb10d01ac36dda
Reference:
http://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1(这一篇很好,有时间应该细读)
http://www.cnblogs.com/likwo/archive/2011/11/01/2232309.html
http://sodecon.blogspot.com/2012/08/ios-multithreading-thread-safety-in-ios.html
http://www.libaocai.com/network/ios/2014/12/30/608
http://blog.csdn.net/zhangao0086/article/details/38904923(这篇关于GCD,还没搞明白T_T)
没有评论:
发表评论