@synchronized(オブジェクト){この@synchronizedというのは「コンパイラディレクティブ」というものです。これは、その後の{}内にある処理を実行している間、引数に指定したオブジェクトをロックし、自身以外のスレッドからアクセスできないようにする働きがあります。こうすることで、そのオブジェクトが常に1つのスレッドしか使えないようにするわけですね。
……実行する処理……
}
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
※MyTestClass.m #import "MyTestClass.h" @implementation MyTestClass +(MyTestClass*)myTestClassToEndCount:(int)n { MyTestClass* obj = [[MyTestClass alloc] init]; [obj setEndCount:n]; return obj; } -(void)setEndCount:(int)n { endcount = n; } -(void)printMessage:(NSString*)s { @synchronized(self){ BOOL flg = YES; count = 0; while (flg) { [NSThread sleepForTimeInterval:1.0]; NSLog(@"%@:%i",s,++count); if (endcount <= count) { flg = NO; NSLog(@"end..."); } } } } @end ※main関数の修正 #import <Foundation/Foundation.h> #import "MyTestClass.h" int main (int argc, const char * argv[]) { @autoreleasepool { MyTestClass* obj = [MyTestClass myTestClassToEndCount:5]; [NSThread detachNewThreadSelector: @selector(printMessage:) toTarget:obj withObject:@"first"]; [NSThread detachNewThreadSelector: @selector(printMessage:) toTarget:obj withObject:@"second"]; NSLog(@"start!!"); // 終了しないようにしておく [[NSRunLoop currentRunLoop] run]; } return 0; }
<< 前へ |