JavaセマフォとMutex–Java同時実行マルチスレッドとは例で説明されています
公開: 2015-03-12Javaの並行性は非常に幅広いトピックです。 使用できるチュートリアルと例は何百もあります。 しばらく前に、Javaでの複数のスレッドの同時実行とさまざまなタイプの同期ブロックに関するチュートリアルをいくつか作成しました。
このチュートリアルでは、以下について説明します。
- Mutexの説明
- セマフォの説明
- 詳細を含む2つの例
始めましょう
以下Let's keep this in mind
てください。
- 買い物客と顧客の例を見てみましょう
- 買い物客はノートパソコンを借りています
- 顧客はラップトップに来て使用できます–顧客はラップトップを使用するためのキーが必要です
- 使用後–お客様はノートパソコンを買い物客に返却できます
Mutexとは(1スレッドのみ):
買い物客はラップトップの鍵を持っています。 一度に1人の顧客が鍵を持っている(ラップトップを借りる)ことができます。 タスクが終了すると、買い物客はキュー内の次の顧客にキーを渡します(解放します)。
Official Definition
:
「ミューテックスは通常、複数のスレッドでcannot be executed concurrently
re-entrant code
のセクションへのアクセスをシリアル化するために使用されます。 ミューテックスオブジェクトは、制御されたセクションへの1つのスレッドのみを許可し、そのセクションへのアクセスを取得しようとする他のスレッドは、最初のスレッドがそのセクションから出るまで待機するように強制します。」
言い換えると、 Mutex = Mutually Exclusive Semaphore
セマフォとは(N個の指定されたスレッド):
今、ショッパーが3つの同一のラップトップと3つの同一のキーを持っているとしましょう。 セマフォは、 free identical Laptop keys
の数です。 セマフォカウント(キーの数)は最初は3に設定され(3つのラップトップはすべて無料です)、顧客が来るとカウント値が減少します。すべてのラップトップが使用されている場合、つまり、ラップトップの場合、セマフォカウントは0です。これで、顧客のいずれかがラップトップを返却すると、セマフォが1(1つのフリーキー)に増加し、キュー内の次の顧客に渡されます。
Official Definition
:「セマフォは、共有リソースの同時ユーザー数を最大数に制限します。 スレッドは、リソースへのアクセスを要求し(セマフォをデクリメント)、リソースの使用が終了したことを通知できます(セマフォをインクリメントします)。」
別の必読:シングルトンスレッドセーフインスタンスの遅延作成
例-1 :(以下の説明)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
package crunchify . com . tutorial ; import java . util . LinkedList ; import java . util . concurrent . Semaphore ; /** * @author Crunchify.com * */ public class CrunchifySemaphoreMutexTutorial { static Object crunchifyLock = new Object ( ) ; static LinkedList <String> crunchifyList = new LinkedList <String> ( ) ; // Semaphore maintains a set of permits. // Each acquire blocks if necessary until a permit is available, and then takes it. // Each release adds a permit, potentially releasing a blocking acquirer. static Semaphore semaphore = new Semaphore ( 0 ) ; static Semaphore mutex = new Semaphore ( 1 ) ; // I'll producing new Integer every time static class CrunchifyProducer extends Thread { public void run ( ) { int counter = 1 ; try { while ( true ) { String threadName = Thread . currentThread ( ) . getName ( ) + counter ++ ; mutex . acquire ( ) ; crunchifyList . add ( threadName ) ; System . out . println ( "Producer is prdoucing new value: " + threadName ) ; mutex . release ( ) ; // release lock semaphore . release ( ) ; Thread . sleep ( 500 ) ; } } catch ( Exception x ) { x . printStackTrace ( ) ; } } } // I'll be consuming Integer every stime static class CrunchifyConsumer extends Thread { String consumerName ; public CrunchifyConsumer ( String name ) { this . consumerName = name ; } public void run ( ) { try { while ( true ) { // acquire lock. Acquires the given number of permits from this semaphore, blocking until all are // available // process stops here until producer releases the lock semaphore . acquire ( ) ; // Acquires a permit from this semaphore, blocking until one is available mutex . acquire ( ) ; String result = "" ; for ( String value : crunchifyList ) { result = value + "," ; } System . out . println ( consumerName + " consumes value: " + result + "crunchifyList.size(): " + crunchifyList . size ( ) + "\n" ) ; mutex . release ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void main ( String [ ] args ) { new CrunchifyProducer ( ) . start ( ) ; new CrunchifyConsumer ( "Crunchify" ) . start ( ) ; new CrunchifyConsumer ( "Google" ) . start ( ) ; new CrunchifyConsumer ( "Yahoo" ) . start ( ) ; } } |
上記のチュートリアルで、 CrunchifyProducer
は、 CrunchifySemaphoreMutexTutorial.java
がthreadName
をcrunchifyList
オブジェクトに追加すると、セマフォに信号を送ることができます。
CrunchifyConsumer
は、セマフォを取得しようとしている可能性があるため、CrunchifyProducerがthreadIDが追加されたことを通知するまで待機します。 追加されたデータを通知すると、コンシューマーの1つがウェイクアップされ、crunchifyListオブジェクトを読み取ることができることがわかります。 リストを読み取ってから、セマフォの取得に戻ることができます。
その間にプロデューサーが別のパケットを書き込んだ場合、それは再びシグナルを送信し、コンシューマーのいずれかが別のパケットを読み取ります。
言い換えると:
1 2 3 |
CrunchifyProducer : Add an object o List - Semaphore . release ( 1 ) CrunchifyConsumer x N ) - Semaphore . acquire ( 1 ) - Read an object from List |

結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Producer is prdoucing new value : Thread - 01 Crunchify consumes value : Thread - 01 , crunchifyList . size ( ) : 1 Producer is prdoucing new value : Thread - 02 Google consumes value : Thread - 02 , crunchifyList . size ( ) : 2 Producer is prdoucing new value : Thread - 03 Yahoo consumes value : Thread - 03 , crunchifyList . size ( ) : 3 Producer is prdoucing new value : Thread - 04 Crunchify consumes value : Thread - 04 , crunchifyList . size ( ) : 4 . . . . . . . . . . . . . . . |
競合状態を防ぐ方法:
What if you have multiple Consumers?
上記のJavaチュートリアルでは、競合状態を防ぐために、(プロデューサーではなく)コンシューマーがパケットを読み取るときに(セマフォを取得するときではなく)バッファーをロックする必要があります。 以下の例では、すべてが同じJVM上にあるため、プロデューサーもリストをロックします。
例-2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package crunchify . com . tutorial ; import java . util . concurrent . Semaphore ; /** * @author Crunchify.com * */ public class CrunchifyJavaSemaphoreTutorial { private static final int MAX_CONCURRENT_THREADS = 2 ; private final Semaphore crunchifyAdminLOCK = new Semaphore ( MAX_CONCURRENT_THREADS , true ) ; public void crunchifyStartTest ( ) { for ( int i = 0 ; i < 10 ; i ++ ) { CrunchifyPerson person = new CrunchifyPerson ( ) ; person . start ( ) ; } } public class CrunchifyPerson extends Thread { @Override public void run ( ) { try { // Acquire Lock crunchifyAdminLOCK . acquire ( ) ; } catch ( InterruptedException e ) { System . out . println ( "received InterruptedException" ) ; return ; } System . out . println ( "Thread " + this . getId ( ) + " start using Crunchify's car - Acquire()" ) ; try { sleep ( 1000 ) ; } catch ( Exception e ) { } finally { // Release Lock crunchifyAdminLOCK . release ( ) ; } System . out . println ( "Thread " + this . getId ( ) + " stops using Crunchify's car - Release()\n" ) ; } } public static void main ( String [ ] args ) { CrunchifyJavaSemaphoreTutorial test = new CrunchifyJavaSemaphoreTutorial ( ) ; test . crunchifyStartTest ( ) ; } } |
結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
Thread 11 start using Crunchify 's car - Acquire() Thread 10 start using Crunchify' s car - Acquire ( ) Thread 10 stops using Crunchify 's car - Release() Thread 12 start using Crunchify' s car - Acquire ( ) Thread 13 start using Crunchify 's car - Acquire() Thread 11 stops using Crunchify' s car - Release ( ) Thread 13 stops using Crunchify 's car - Release() Thread 15 start using Crunchify' s car - Acquire ( ) Thread 14 start using Crunchify 's car - Acquire() Thread 12 stops using Crunchify' s car - Release ( ) Thread 14 stops using Crunchify 's car - Release() Thread 16 start using Crunchify' s car - Acquire ( ) Thread 15 stops using Crunchify 's car - Release() Thread 17 start using Crunchify' s car - Acquire ( ) Thread 17 stops using Crunchify 's car - Release() Thread 18 start using Crunchify' s car - Acquire ( ) Thread 19 start using Crunchify 's car - Acquire() Thread 16 stops using Crunchify' s car - Release ( ) Thread 18 stops using Crunchify 's car - Release() Thread 19 stops using Crunchify' s car - Release ( ) |