我是Java的新手,试图通过实现来学习Java概念。 这里ReentrantLock类的原因是理解Locks。
我正在产生3个线程,在这些线程中我只增加一个全局计数器。 我正在使用Locks保护计数器覆盖其他线程。
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应用程序,这导致了Expected Output和观察输出的差异。
答案 0 :(得分:1)
问题是每个线程对象都有自己的锁(并且能够独立于所有其他线程正在执行的操作而锁定它):
private final ReentrantLock myLock = new ReentrantLock();
如果您希望跨线程共享锁,请创建上述对象static
。