日期:2014-05-20  浏览次数:20716 次

java 正在操作的Integer不能加锁吗?
public class TestVolitile extends Thread {

TestVolitile(int id) {
this.setName("thread :" + id);
}

public static Integer n = new Integer(0);
public static byte[] lock=new byte[0];

public void run() {
synchronized (n) {
// System.err.println(getName() + "  n " + n);
for (int i = 0; i < 3; i++) {
n++;
try {
sleep(1);
} catch (InterruptedException e) {
} // 为了使运行结果更随机,延迟3毫秒
}
// System.err.println(getName() + "  end " + n);
}
}

static void runTest() throws InterruptedException{
Thread threads[] = new Thread[1000];
for (int i = 0; i < threads.length; i++)
// 建立100个线程
threads[i] = new TestVolitile(i);
for (int i = 0; i < threads.length; i++)
// 运行刚才建立的100个线程
threads[i].start();
for (int i = 0; i < threads.length; i++)
// 100个线程都执行完后继续
threads[i].join();
System.out.println(" n= " + TestVolitile.n);
TestVolitile.n=0;
}

public static void main(String[] args) throws Exception {
for (int i = 0; i < 50; i++) {
runTest();
}
}
}


为什么n锁不住,换一个lock就可以了呢?
同步,并发

------解决方案--------------------
你说使用 public static byte[] lock=new byte[0] 就好了?为什么?因为你在代码中,没有对这个变量进行修改,public static byte[] lock=new byte[0] 和我上面写的
private Object obj = new Object();
synchronized (obj)

synchronized (this)
没有任何的区别,都是对象的内置锁。同步它,都是线程安全的。你的
public static Integer n = new Integer(0);
被你进行 n++; 操作修改了。