#import "Thread.h"
@implementation Thread
- (void)thread1
{
//1. 不需要手动设置线程启动,自动启动该线程。
[NSThread detachNewThreadSelector:@selector(myThreadMethod:) toTarget:self withObject:nil] ;
//2. 需要设置启动模式,也可以设置线程优先级
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(myThreadMethod2:) object:nil];
[thread start];
//3. 间接方式,与第一种相似,不需要手动启动线程
[self performSelectorInBackground:@selector(myThreadMethod3:) withObject:nil];
//
[self performSelector:@selector(myThreadMethod4:) onThread:thread withObject:nil waitUntilDone:NO];
[thread release];
}
- (void)myThreadMethod:(id)arg
{
for (int i = 0; i < 10; i ++){
[NSThread sleepForTimeInterval:1];
NSLog(@"hello wolrd");
}
}
- (void)myThreadMethod2:(id)arg
{
for (int i = 0; i < 10; i ++){
[NSThread sleepForTimeInterval:1];
NSLog(@"thread 2 ...");
}
}
- (void)myThreadMethod3:(id)arg
{
for (int i = 0; i < 10; i ++){
[NSThread sleepForTimeInterval:1];
NSLog(@"thread 3 ...");
}
}
- (void)myThreadMethod4:(id)arg
{
for (int i = 0; i < 10; i ++){
[NSThread sleepForTimeInterval:1];
NSLog(@"thread 4 ...");
}
}
2013-11-22 17:37:04.124 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:04.124 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:04.124 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:05.128 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:05.128 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:05.128 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:06.131 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:06.131 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:06.131 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:07.133 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:07.133 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:07.133 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:08.135 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:08.135 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:08.135 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:09.138 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:09.138 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:09.138 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:10.141 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:10.141 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:10.141 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:11.143 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:11.143 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:11.143 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:12.145 Project2_OC[3191:2503] thread 3 ...
2013-11-22 17:37:12.145 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:12.145 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:13.147 Project2_OC[3191:1903] hello wolrd
2013-11-22 17:37:13.147 Project2_OC[3191:1a03] thread 2 ...
2013-11-22 17:37:13.147 Project2_OC[3191:2503] thread 3 ...