iOS线程间通信_iOS开启while1线程

iOS线程间通信_iOS开启while1线程什么叫做线程间通信 在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程  在1个线程中执行完特定任务后,转到另1个线程继续执行任务 线程间通信常用方法1.NSThread:一个线程传递数据给另一个线程-(void)performSelectorOnMainThread:(SEL)aSelectorwi…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

什么叫做线程间通信

  •  在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信

 线程间通信的体现

  •  1个线程传递数据给另1个线程
  •   在1个线程中执行完特定任务后,转到另1个线程继续执行任务

 线程间通信常用方法

1. NSThread :一个线程传递数据给另一个线程

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5, 2_0);

//具体用法如下:
//点击屏幕开始执行下载方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self performSelectorInBackground:@selector(download) withObject:nil];
}

//下载图片
- (void)download
{    
    // 1.图片地址
    NSString *urlStr = @"http://d.jpg"; 
    NSURL *url = [NSURL URLWithString:urlStr]; 
    // 2.根据地址下载图片的二进制数据 
    NSData *data = [NSData dataWithContentsOfURL:url]; 
    // 3.设置图片
    UIImage *image = [UIImage imageWithData:data]; 
    // 4.回到主线程,刷新UI界面(为了线程安全)
    [self performSelectorOnMainThread:@selector(downloadFinished:) withObject:image waitUntilDone:NO]; 
   // [self performSelector:@selector(downloadFinished:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES]; 
    
}

- (void)downloadFinished:(UIImage *)image
{
    self.imageView.image = image; 
    NSLog(@"downloadFinished---%@", [NSThread currentThread]);
}
 

2. GCD :一个线程传递数据给另一个线程

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event    
{  
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSLog(@"donwload---%@", [NSThread currentThread]);
        
        // 1.子线程下载图片
        NSURL *url = [NSURL URLWithString:@"http://d.jpg"];
        
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        UIImage *image = [UIImage imageWithData:data];
        
        // 2.回到主线程设置图片
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"setting---%@ %@", [NSThread currentThread], image);
            
            [self.button setImage:image forState:UIControlStateNormal];
        });
    });
}
 

3. NSMachPort 

NSPort有3个子类,NSSocketPort、NSMessagePort、NSMachPort,但在iOS下只有NSMachPort可用。

#define kMsg1 100
#define kMsg2 101
 
- (void)viewDidLoad {
    [super viewDidLoad]; 
    //1. 创建主线程的port
    // 子线程通过此端口发送消息给主线程
    NSPort *myPort = [NSMachPort port]; 
    //2. 设置port的代理回调对象
    myPort.delegate = self; 
    //3. 把port加入runloop,接收port消息
    [[NSRunLoop currentRunLoop] addPort:myPort forMode:NSDefaultRunLoopMode]; 
    //4. 启动次线程,并传入主线程的port
    MyWorkerClass *work = [[MyWorkerClass alloc] init];
    [NSThread detachNewThreadSelector:@selector(launchThreadWithPort:)
                             toTarget:work
                           withObject:myPort];
}

- (void)handlePortMessage:(NSMessagePort*)message{ 
    NSLog(@"接到子线程传递的消息!%@",message); 
    //1. 消息id
    NSUInteger msgId = [[message valueForKeyPath:@"msgid"] integerValue]; 
    //2. 当前主线程的port
    NSPort *localPort = [message valueForKeyPath:@"localPort"]; 
    //3. 接收到消息的port(来自其他线程)
    NSPort *remotePort = [message valueForKeyPath:@"remotePort"];
 
    if (msgId == kMsg1)
    {
        //向子线的port发送消息
        [remotePort sendBeforeDate:[NSDate date]
                             msgid:kMsg2
                        components:nil
                              from:localPort
                          reserved:0];
 
    }else if (msgId == kMsg2){
        NSLog(@"操作2....\n");
    }
}
//MyWorkerClass类

#import "MyWorkerClass.h"
 
@interface MyWorkerClass() <NSMachPortDelegate> {
    NSPort *remotePort;
    NSPort *myPort;
}
@end
 
#define kMsg1 100
#define kMsg2 101
 
@implementation MyWorkerClass
 
- (void)launchThreadWithPort:(NSPort *)port {
 
    @autoreleasepool {
        //1. 保存主线程传入的port
        remotePort = port;
        //2. 设置子线程名字
        [[NSThread currentThread] setName:@"MyWorkerClassThread"];
        //3. 开启runloop
        [[NSRunLoop currentRunLoop] run];
        //4. 创建自己port
        myPort = [NSPort port];
        //5.
        myPort.delegate = self;
        //6. 将自己的port添加到runloop
        //作用1、防止runloop执行完毕之后推出
        //作用2、接收主线程发送过来的port消息
        [[NSRunLoop currentRunLoop] addPort:myPort forMode:NSDefaultRunLoopMode];
        //7. 完成向主线程port发送消息
        [self sendPortMessage];
    }
}
 
/**
 *   完成向主线程发送port消息
 */
- (void)sendPortMessage {
 
    NSMutableArray *array  =[[NSMutableArray alloc]initWithArray:@[@"1",@"2"]];
    //发送消息到主线程,操作1
    [remotePort sendBeforeDate:[NSDate date]
                         msgid:kMsg1
                    components:array
                          from:myPort
                      reserved:0]; 
}
 
#pragma mark - NSPortDelegate
/**
 *  接收到主线程port消息
 */
- (void)handlePortMessage:(NSPortMessage *)message
{
    NSLog(@"接收到父线程的消息...\n"); 
}
 
@end

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/185177.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • staruml使用教程[通俗易懂]

    最近因为实验需要,得用到uml类图。找了个教程。mark下,便于以后学习。 http://blog.csdn.net/monkey_d_meng/article/details/5995610

    2022年4月12日
    48
  • Git 常用命令

    Git 常用命令

    2021年9月17日
    47
  • 小波变换–dwt2 与wavedec2

    小波变换–dwt2 与wavedec2https://www.cnblogs.com/xfzhang/p/7295041.htmlhttps://www.ilovematlab.cn/thread-45020-1-1.htmldwt2是二维单尺度小波变换,其可以通过指定小波或者分解滤波器进行二维单尺度小波分解。而wavedec2是二维多尺度小波分解.尺度可理解为级,即wavedec2可用于多级小波分解dwt2:[cA,cH,cV,cD]=dwt2(X,’wname’);wavedec2:[C,S]=wavede…

    2022年7月23日
    10
  • Win10安装程序修复计算机,directx修复工具win10最新版

    Win10安装程序修复计算机,directx修复工具win10最新版directx修复工具win10最新版是一款以排除电脑软件异常导致的无法正常使用问题而特别打造的优质工具。全自动的智能检测修复功能能够确保用户们因为程序问题而导致的电脑异常无法使用都得到解决。directx修复工具win10最新版功能1、Directx修复增强版是一个系统DirectX组件修复工具,主要用于检测当前系统的DirectX状态。2、发现异常就进行修复。DirectX修复工具可以完美解决…

    2022年6月6日
    26
  • 二级导航菜单[通俗易懂]

    二级导航菜单[通俗易懂]本文用html5+css实现了二级导航菜单,二级导航菜单在网站建设中使用的越来越广泛。效果图如下:当鼠标悬停在一级菜单上时,出现二级下拉菜单二级下拉菜单可以被选中,当鼠标悬停上去时,变色。html代码&lt;!DOCTYPEhtml&gt;&lt;html&gt;&lt;head&gt;&lt;metacharset="UTF-…

    2022年7月26日
    8
  • js 二维数组 添加json数据及js数组与json字符串「建议收藏」

    js 二维数组 添加json数据及js数组与json字符串「建议收藏」 JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,JSON是JavaScript原生数据格式。下面给大家介绍js数组添加json数据的两种方式。//第一种方式? 1 2 3 4 5 6 7 personInfo :[],…

    2022年5月27日
    96

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号