直接上代碼:
import java.util.concurrent.locks.ReentrantLock;
public class MulThreadTest {
public static int a = 0;
ReentrantLock lock = new ReentrantLock(true);
public void addInt(){
lock.lock();
a++;
System.out.println(Thread.currentThread().getName()+"___________"+a +"_ " + lock.getHoldCount());
lock.unlock();
}
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<3;i++){
new Thread(new Runnable() {
@Override
public void run() {
MulThreadTest test = new MulThreadTest();
for(int j=0;j<100;j++)
test.addInt();
}
},"thread"+i).start();
}
}
}
運行結果總會丟數字,難道是使用方法有問題?幫忙解答一下~
你在每個線程裡都建立了不同的text,也就是有三個不同的a在三個不同的test的實例裡,這樣改就可以了,三個線程訪問的是同一個test實例,addInt也是針對同一個a,這樣輸出就可以看出lock的作用了
import java.util.concurrent.locks.ReentrantLock;
public class MulThreadTest {
public static int a = 0;
ReentrantLock lock = new ReentrantLock(true);
public void addInt(){
lock.lock();
a++;
System.out.println(Thread.currentThread().getName()+"___________"+a +"_ " + lock.getHoldCount());
lock.unlock();
}
public static void main(String[] args) throws InterruptedException {
final MulThreadTest test = new MulThreadTest();
for(int i=0;i<3;i++){
new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<100;j++)
test.addInt();
}
},"thread"+i).start();
}
}
}