javaマルチスレッド方法メモ【上】

2051 ワード

仕事を始めたばかりで、主にc++を使ってサーバーを書きますが、たまにjavaとpythonを使って勉強します。まず、javaマルチスレッドから開始します。
javaマルチスレッドの基本的な方法:
//       
public void start( );  
//       run
public void run( );  
//    ,     
//           
public static void sleep(long millis) throws InterruptedException;  
//           ,                    
public static void sleep(long millis, int nanos) throws InterruptedException;  
//     
public static void yield(); 
 
//wait   notify  notifyAll  ,      ,      runnable   
//wait(),notify(),notifyAll()   Thread ,    Object    
//wait(),notify(),notifyAll()    synchronized    
//  notify()  ,      ,wait()                  runnable  
//   notify wait            ,     notify   wait,       wait,        currentthread 。 
public final native void wait() throws InterruptedException;
public final native void wait(long millis) throws InterruptedException;
public final native void wait(long millis, int nanos) throws InterruptedException;
public final native void notify();
public final native void notifyAll(); 
 
//        
//sleep wait    InterruptedException               , 
//       true ,  InterruptedException   
//     isInterrupted interrupted        
public void interrupt( );  

//         
public boolean isAlive( );  
//interrupted         ,isInterrupted                     。 
//     interrupted             ,isInterrupted                      
public boolean isInterrupted( );  
public static boolean interrupted( );  
 
// join  ,block           
public void join() throws InterruptedException;
public void join(long millis) throws InterruptedException; 
public void join(long millis, int nanos) throws InterruptedException; 
 
//         
public final void setDaemon(boolean on);
スレッド同期キーワードsynchronized:複数のスレッドが同じリソースにアクセスする場合、synchronizedでセキュリティを保証します。
各クラスの例にはロックがあり、synchronizedはロックをかけるプロセスであり、方法にも使用され、プログラムブロックにも使用され得る。
静的なsynchronizedは、一般的にクラス静的なメンバの動作の安全性を制御するために使用される。
volatileキーワード:簡単変数が使用できます。注:変数の値が自分の前のもので決定されると、n=n+1,n++などのようにvolatileキーワードが無効になります。この場合は、変数をsynchronizedでカプセル化する必要があります。