首页 技术 正文
技术 2022年11月6日
0 收藏 743 点赞 519 浏览 1718 个字

#import “ViewController.h”

//导入头文件

#import <pthread.h>

@interfaceViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

[superviewDidLoad];

[selfbtnClick];

}

/*

*NSThread创建线程方式

*1.先初始化线程

*2.start开启线程

*/

-(void)btnClick

{

//1.获取当前线程

NSThread * current = [NSThreadcurrentThread];

//主线程

NSLog(@”进入主线程–%@”,current);

//获取主线程的另一中方式

NSThread*main =[NSThreadmainThread];

NSLog(@”主线程2–%@”,main);

//执行一些耗时操作(分多一个线程)

[selfcreatNSTread];

}

-(void)creatNSTread

{

NSThread * thread1=[[NSThreadalloc]initWithTarget:selfselector:@selector(run:) object:@”线程A”];

//设置一个名称

thread1.name=@”线程A”;

//开启线程

[thread1 start];

NSThread * thread2=[[NSThreadalloc]initWithTarget:selfselector:@selector(run:) object:@”线程B”];

//设置一个名称

thread2.name=@”线程B”;

//开启线程

[thread2 start];

}

-(void)run:(NSString*)str

{

//获取当前线程

NSThread * current=[NSThreadcurrentThread];

//打印输出

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

NSLog(@”run–%@–%@”,current,str);

}

}

运行结果:

第一篇:NSTread线程的创建

/******************************创建NSTread线程方式2**************************************/

#import “ViewController.h”

//导入头文件

#import <pthread.h>

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

[super viewDidLoad];

[self btnClick];

}

-(void)btnClick

{

//1.获取当前线程

NSThread * current = [NSThread currentThread];

//主线程

NSLog(@”进入主线程–%@”,current);

//获取主线程的另一中方式

NSThread*main =[NSThread mainThread];

NSLog(@”主线程2–%@”,main);

//执行一些耗时操作(分多一个线程)

[self creatNSTread2];

[self creatNSTead3];

}

/*

*NSTread创建线程方式2

*创建完线程直接启动(自动)

*/

-(void)creatNSTread2

{

[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@”第一线程”];

}

-(void)creatNSTead3

{

//在后台线程执行在子线程中执行

[self performSelectorInBackground:@selector(run:) withObject:@”第二线程”];

}

-(void)run:(NSString*)str

{

//获取当前线程

NSThread * current=[NSThread currentThread];

//打印输出

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

NSLog(@”run–%@–%@”,current,str);

}

}

运行结果:

第一篇:NSTread线程的创建

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,413
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,186
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905