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();
}
}
}