iOS多线程学习笔记之二:线程创建与启动

来源:互联网 发布:张继科垃圾知乎 编辑:程序博客网 时间:2024/04/29 22:08
原文地址:iOS多线程学习笔记之二:线程创建与启动作者:wingsmm

线程创建与启动

NSThread的创建主要有两种直接方式:

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

NSThread myThread =[[NSThread allocinitWithTarget:self selector:@selector(myThredaMethod:) object:nil];

[myThread start];CocoaLigature1 

 

这两种方式的区别是:

前一种一调用就会立即创建一个线程来做事情;

而后一种虽然你 alloc 了也 init了,但是要直到我们手动调用 start 启动线程时才会真正去创建线程。

这种延迟实现思想在很多跟资源相关的地方都有用到。后一种方式我们还可以在启动线程之前,对线程进行配置,比如设置 stack 大小,线程优先级。

 

还有一种间接的方式,更加方便,我们甚至不需要显式编写 NSThread 相关代码,

那就是利用 NSObject 的类方法 performSelectorInBackground:withObject: 来创建一个线程:CocoaLigature0 

[myobject performSelectorInBackground:@selector(myThredaMethod:) withObject:nil];

CocoaLigature1 其效果与 NSThread 的 detachNewThreadSelector:toTarget:withObject: 是一样的。

[转载]iOS多线程学习笔记之二:线程创建与启动

 

@interface ThreadViewController UIViewController {

    UIProgressView *progressView;

    UILabel *label;

    NSThread *thr;

}

@property (nonatomicretainIBOutlet UIProgressView *progressView;

@property (nonatomicretainIBOutlet UILabel *label;

 

(IBActionstartProgress:(id)sender;

@end

@implementation ThreadViewController

 

@synthesize progressView,label;

 

(void)dealloc

{

    [progressView release];

    [label release];

    [super dealloc];

}

 

(void)viewDidUnload

{

    [super viewDidUnload];

    self.progressView nil;

    self.label nil;

}

 ……

#define UPDATE_IN_MAINTHREAD 1

(voidupdateProgress:(id)arg

{

    float currentValue [progressView progress];

    progressView.progress currentValue 0.01;

    label.text [NSString stringWithFormat:@".0f%%"progressView.progress*100];

    NSLog(@"current value %f"currentValue);

 

}

(voidbeginDownload:(id)arg

{

    NSAutoreleasePool *pool [[NSAutoreleasePool allocinit];

    NSLog(@"begin to download ");


    for (int 0100i++) {

        [NSThread sleepForTimeInterval:0.2f];

#if UPDATE_IN_MAINTHREAD

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

#else

        [self updateProgress:nil];

#endif

    }

    [pool release];

}

 

(IBActionstartProgress:(id)sender

{

    progressView.progress 0.0f;

    label.text [NSString stringWithFormat:@".0f%%"progressView.progress*100];

 

    NSLog(@"start progress");

#if 0

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

#else

    thr [[NSThread allocinitWithTarget:self selector:@selector(beginDownload:) object:nil];

    [thr start];

#endif

}

@end