import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestMain {
static volatile int count = 0;
Lock lock = new ReentrantLock();
Object obj = new Object();
public static void main(String[] str){
for(int i=0;i<1000;i++){
TestMain tm = new TestMain();
Stuff stuff = tm.new Stuff();
stuff.setName("thread:"+i);
stuff.start();
}
while(Thread.activeCount()>1)Thread.yield();
System.out.print(count);
}
class Stuff extends Thread{
public Stuff(){};
@Override
public void run(){
//Lock lock = new ReentrantLock();
for(int i=0;i<100;i++){
synchronized(obj){
count++;
}
}
}
}
我不是对变量加了锁了吗?为何不行呢?但是下面的写法却可以?
public int inc = 0;
Lock lock =new ReentrantLock();
public void increase(){
lock.lock();
try{
inc++;
}finally{
lock.unlock();
}
}
public static void main(String[] args){
final TestMain2 test = new TestMain2();
for(int i=0;i<100;i++){
new Thread(){
public void run(){
for(int j = 0;j<1000;j++)test.increase();
}
}.start();
}
while(Thread.activeCount()>1)Thread.yield();
System.out.println(test.inc);
}