//这只是一个更好理解的示例。我想了解是否有必要锁定我不知道此示例是否适合我想要了解的内容。 ................................................... ................................................... ................................................... ..................
class Counter{
int counter;
public ReentrantLock lock=new ReentrantLock();
//if the variable is visible to more Threads all readings and writes must be Thread-safe?
public void incr() {
lock.lock();
try {
counter++;
} finally {
lock.unlock();
}
}
public void decr() {
lock.lock();
try {
counter--;
} finally {
lock.unlock();
}
}
//must have Lock
public int getincr() {
return counter;
}
}
//these are the Thread
public class Worker extends Thread {
private Counter c;
public Worker (Counter c) {
this.c=c;
}
enter code here
public void run() {
System.out.println(Thread.currentThread().getName());
for(int i=1;i<=10;i++) {
c.incr(); System.out.println(c.getincr());//this is the method
c.decr(); System.out.println(c.getincr());
}
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//Main
public class Test {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Counter c=new Counter();
Worker[] threads = new Worker[100];
for(int i=0;i<100;i++) {
threads[i]=new Worker(c);
threads[i].start();
//threads[i].join();
}
}
}
尝试在主方法的末尾添加以下两行,然后添加和删除锁定代码。
Thread.sleep(10000);
System.out.println("Final counter value: " + c.counter)
如果您多次运行main方法,将会看到以下内容:
对上述行为的解释是,在锁定的情况下,正在访问的计数器的值始终是正确的。由于递增和递减在使用计数器变量之前都使用相同的显式锁定对象,因此JVM保证您将拥有该变量的最新值。