#import "ViewController.h"
#import "XMGThread.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self createThread3];
}
//需要启动线程,可以设置线程
-(void)createThread1
{
//1.创建线程对象
/*
第一个参数:目标对象self
第二个参数:要调用的方法
第三个参数:要调用方法的参数,nil
*/
//当线程里面的任务执行完毕之后,线程被释放
XMGThread *thread = [[XMGThread alloc]initWithTarget:self selector:@selector(run:) object:@"创建线程"];
NSLog(@"%@",[NSThread mainThread]);
//设置线程属性
thread.name = @"线程A";
thread.threadPriority = 1.0; //设置优先级 0.0~1.0 默认是0.5 最高是1.0
//2.启动线程
[thread start];
NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:nil];
thread2.name = @"线程B";
thread2.threadPriority = 0.1;
[thread2 start];
NSThread *thread3 = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:nil];
thread3.name = @"线程C";
[thread3 start];
}
//第二种:分离出一条子线程,自动启动,不能详细的设置线程对象
-(void)createThread2
{
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"分离线程"];
}
//第三种:开启后台线程,自动启动,不能详细的设置线程对象
-(void)createThread3
{
[self performSelectorInBackground:@selector(run:) withObject:@"123"];
}
-(void)run:(NSString *)param
{
for (NSInteger i = 0;i<10;i++) {
NSLog(@"%@---%@--%zd",param,[NSThread currentThread],i);
}
}
@end