为什么新线程指向主线程?

时间:2017-05-09 07:25:02

标签: ios objective-c multithreading

首先,我的财产很弱。它指向不是主线程的线程。

@property (nonatomic, weak) id weakThread;

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    {
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil];
        self.weakThread = thread;
        [thread start];
    }
    NSLog(@"main: %@, %p", self.weakThread, self.weakThread);
    return YES;
}

- (void)threadRun {
    NSLog(@"current: %@, %p", [NSThread currentThread], [NSThread currentThread]);
    NSLog(@"self.weakThread in thread: %@, %p", self.weakThread, self.weakThread);
}

看看这些代码。运行后,这是输出:

main: <NSThread: 0x608000278240>{number = 5, name = main}, 0x608000278240
current: <NSThread: 0x608000278240>{number = 5, name = (null)}, 0x608000278240
self.weakThread in thread: <NSThread: 0x608000278240>{number = 5, name = (null)}, 0x608000278240

指针永远不会改变。但线程发生了变化。我不知道为什么它被改为主线程。 你看到第一个输出,名称是main。

1 个答案:

答案 0 :(得分:1)

实际上,代码中的self.weakThread[NSThread currentThread]是相同的,因此不需要更改指针。它没有改为主线程(名称'main'是假的)。您可以通过为线程指定名称来证明它:

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil];
thread.name = @"a thread";

结果将更改为

"{number = 5, name = a thread}". 

你会发现真正的主线程具有不同的地址:

NSLog(@"real main: %@", [NSThread mainThread]);
NSLog(@"my thread: %@", self.weakThread);