私はJavaの初心者で、実装でJavaの概念を学ぼうとしています。ここで ReentrantLock クラスを使用する理由は、ロックを理解するためです。
私は 3 つのスレッドを生成しています。これらのスレッドでは、グローバル カウンターをインクリメントするだけです。ロックを使用して、他のスレッドによるカウンターの上書きを保護しています。
import java.util.concurrent.locks.ReentrantLock;
class ReentryHandledSingleThread extends Thread
{
static long counter = 0;
private int myId;
private final ReentrantLock myLock = new ReentrantLock();
public ReentryHandledSingleThread(int id)
{
this.myId = id;
}
public void incrementTheCounter()
{
long stackvariable;
int i;
for (i = 0; i < 10000; i++)
{
stackvariable = ReentryHandledSingleThread.counter;
stackvariable = stackvariable + 1;
ReentryHandledSingleThread.counter = stackvariable;
}
System.out.println("The value from counter is " + ReentryHandledSingleThread.counter);
return;
}
public void run()
{
System.out.println("Started Thread No. " + this.myId);
this.myLock.lock();
{
System.out.println("LOCKED Thread No. " + this.myId);
this.incrementTheCounter();
}
System.out.println("UNLOCKED Thread No." + this.myId);
this.myLock.unlock();
}
}
public class RentryHandle
{
public static void main(String[] args)
{
System.out.println("Started Executing Main Thread");
int noOfThreads = 3;
ReentryHandledSingleThread threads[] = new ReentryHandledSingleThread[noOfThreads];
for (int j = 0; j < noOfThreads; j++)
{
threads[j] = new ReentryHandledSingleThread(j);
}
for (int j = 0; j < noOfThreads; j++)
{
threads[j].start();
}
for (int j = 0; j < noOfThreads; j++)
{
try
{
threads[j].join();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finished Executing Main thrread");
}
}
上記のコードからの観察された出力
Started Executing Main Thread
Started Thread No. 0
LOCKED Thread No. 0
Started Thread No. 2
LOCKED Thread No. 2
The value from counter is 10226
UNLOCKED Thread No.0
The value from counter is 16165
UNLOCKED Thread No.2
Started Thread No. 1
LOCKED Thread No. 1
The value from counter is 26165
UNLOCKED Thread No.1
Finished Executing Main thrread
私の期待される出力
Started Executing Main Thread
Started Thread No. 0
LOCKED Thread No. 0
The value from counter is 10000
UNLOCKED Thread No.0
Started Thread No. 1
LOCKED Thread No. 1
The value from counter is 20000
UNLOCKED Thread No.1
Started Thread No. 2
LOCKED Thread No. 2
The value from counter is 30000
UNLOCKED Thread No.2
Finished Executing Main thrread
私 は reentrantlock -lock-doesnt-block-other-threadsを経験しましたが、ここでは使用していません
Condition.await()
したがって、実装と相互に関連付けることができませんでした。間違いを理解するか、ReentrantLock アプリケーションを実装で理解するのを手伝ってください。これにより、期待される出力と観察される出力が異なります。