public class Test3 extends Thread{
static int i;
public static void main(String[] args) {
Thread a = new Test3();
Thread a2 = new Test3();
a.start();
a2.start();
}
@Override
public void run() {
try {
add();
} catch (Exception e) {
e.printStackTrace();
}
}
public void add() throws Exception
{
String kk = new String ();
synchronized (kk)
{
i++;
Thread.sleep(100);
System.out.println(Thread.currentThread().getId()+"__num:"+i);
}
}
}
为什么我加了锁.可打印的结果仍然是 i 都为2 呢?
请详细说明下原因.
我的想法是. 这个kk不是两个线程共有的.所以不能生效. 不知道对不对. :(