多线程2

2016-06-25  本文已影响18人  艾克12138

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,strong)NSData *data;

@property (weak, nonatomic) IBOutlet UIImageView *imageview;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

}

//主线程回调事件

-(void)updateUi{

NSLog(@"刷新UI");

self.imageview.image =[UIImage imageWithData:self.data];

}

//手动开启线程

- (IBAction)manual:(UIButton *)sender {

NSThread *thread =[[NSThread alloc]initWithTarget:self selector:@selector(threadtest) object:nil];

//开启线程

[thread start];

//结束线程有2种方式:

//取消线程;

[thread cancel];

//立即结束线程

[NSThread exit];

//判断一个线程是否正在执行

[thread isExecuting];

//判断一个线程是否完成了任务

[thread isFinished];

}

//自动开启线程

- (IBAction)outotNSthread:(UIButton *)sender {

[NSThread detachNewThreadSelector:@selector(threadtest) toTarget:self withObject:nil];

NSLog(@"zouni");

}

//线程执行事件

-(void)threadtest{

//线程一定加autorealeasepool

//如果一个任务在子线程中执行,我们需要在任务里面添加autorealeasepool:原因:因为线程与线程之间是相互独立的,但是资源确实共享的在任务里可能会创建多个对象(在堆区开辟)如果没有释放的话,其他线程也无法访问和使用这个开辟的空间;

//主要是针对 在线称执行的任务中,大量使用便利构造器创建对象的时候,可能会造成很多堆区内存无法释放,导致内存泄漏问题.

@autoreleasepool {

//现获取当前线程

NSLog(@" 当前线程%@",[NSThread currentThread]);

//判断是不是主线程

NSLog(@"是不是主线程%d",[[NSThread currentThread]isMainThread]);

//        NSInteger count =0;

//        for (int i=0; i<1000000000; i++) {

//            count +=i;

//

//        }

//        NSLog(@"%ld",(long)count);

self.data =[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic.nipic.com/2007-11-09/200711912453162_2.jpg"]];

}

//回到主线程

[self performSelectorOnMainThread:@selector(updateUi) withObject:nil waitUntilDone:nil];

}

//nsobject主线程

- (IBAction)mainNSobject:(UIButton *)sender {

//在主线程中执行某个方法

[self performSelectorOnMainThread:@selector(threadtest) withObject:nil waitUntilDone:YES];

}

//bsobject子线程

- (IBAction)childthread:(UIButton *)sender {

//在子线称重执行某个事件

[self performSelectorInBackground:@selector(threadtest) withObject:nil];

}

- (IBAction)buttion1:(id)sender {

int count =0;

for (int i=0; i<1000000; i++) {

count += i;

}

NSLog(@"当前线程是:%@,是不是主线程%d",[NSThread currentThread],[[NSThread currentThread] isMainThread]);

NSLog(@"%d",count);

}

上一篇 下一篇

猜你喜欢

热点阅读