作者:孫東風 2009-11-10(請尊重作者勞動成果,轉載務必註明出處)
Java因為其本身支援多線程而給程式員帶來很多方便,其實在iphone的開發中也支援多線程編程,並且一點也不比java麻煩。
在這篇文章中,筆者就拿大多數Java教程中經典的“售票系統多線程”作為實際例子,在iphone中進行同樣的實現。
下面是java版本的“售票系統多線程”代碼:
package demo;
public class SellTickets implements Runnable{
private int tickets=100;
public void run() {
int count=0;
while (true)
{
//上鎖
synchronized(this){
if (tickets>0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
count=100-tickets;
System.out.println("當前票數是:"+tickets+"售出"+count
+"線程名:"+Thread.currentThread().getName());
tickets--;
}else{
break;
}
}
}
}
public static void main(String[] args) {
SellTickets r=new SellTickets();
Thread t1=new Thread(r,"t1");
t1.start();
Thread t2=new Thread(r,"t2");
t2.start();
Thread t3=new Thread(r,"t3");
t3.start();
Thread t4=new Thread(r,"t4");
t4.start();
}
}
以上java版本的代碼執行後控制台輸出如下:
當前票數是:100售出0線程名:t1
當前票數是:99售出1線程名:t2
當前票數是:98售出2線程名:t3
當前票數是:97售出3線程名:t4
當前票數是:96售出4線程名:t1
當前票數是:95售出5線程名:t2
當前票數是:94售出6線程名:t3
當前票數是:93售出7線程名:t4
當前票數是:92售出8線程名:t1
當前票數是:91售出9線程名:t2
當前票數是:90售出10線程名:t3
當前票數是:89售出11線程名:t4
當前票數是:88售出12線程名:t1
當前票數是:87售出13線程名:t2
當前票數是:86售出14線程名:t3
當前票數是:85售出15線程名:t4
當前票數是:84售出16線程名:t1
當前票數是:83售出17線程名:t2
當前票數是:82售出18線程名:t3
當前票數是:81售出19線程名:t4
當前票數是:80售出20線程名:t1
當前票數是:79售出21線程名:t2
當前票數是:78售出22線程名:t3
當前票數是:77售出23線程名:t4
當前票數是:76售出24線程名:t1
當前票數是:75售出25線程名:t2
當前票數是:74售出26線程名:t3
當前票數是:73售出27線程名:t4
……
可以在iphone中進行同樣的實現,Iphone的Frameworks/Foundation.framework架構支援多線程編程,介面定義在:
/Xcode3.1.4/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/System/Library
/Frameworks/Foundation.framework/Headers/NSThread.h
到相應的目錄下開啟此檔案,可以看到絕大多數java中的介面這裡也都能找到相應的實現,如下:
/* NSThread.h
Copyright (c) 1994-2007, Apple Inc. All rights reserved.
*/
#import <Foundation/NSObject.h>
#import <Foundation/NSDate.h>
@class NSArray, NSMutableDictionary, NSDate;
@interface NSThread : NSObject {
@private
id _private;
uint8_t _bytes[44];
}
+ (NSThread *)currentThread;
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
+ (BOOL)isMultiThreaded;
- (NSMutableDictionary *)threadDictionary;
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
+ (void)exit;
#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED
+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
#endif
#if MAC_OS_X_VERSION_10_5 <= MAC_OS_X_VERSION_MAX_ALLOWED
+ (NSArray *)callStackReturnAddresses;
- (void)setName:(NSString *)n;
- (NSString *)name;
- (NSUInteger)stackSize;
- (void)setStackSize:(NSUInteger)s;
- (BOOL)isMainThread;
+ (BOOL)isMainThread; // reports whether current thread is main
+ (NSThread *)mainThread;
- (id)init; // designated initializer
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
- (BOOL)isExecuting;
- (BOOL)isFinished;
- (BOOL)isCancelled;
- (void)cancel;
- (void)start;
- (void)main; // thread body method
#endif