public class thread1 extends Thread {
public void run() {
while (true) {
synchronized (test.i) {
int i = test.i;
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class thread2 extends Thread {
public void run() {
while (true) {
synchronized (test.i) {
int i = test.i;
i++;
test.i = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class test { public static int i = 0; public static void main(String[] args) {
thread1 t1 = new thread1();
thread2 t2 = new thread2();
t1.start();
t2.start();
}
}
这样写会报错,为什么,应该怎么改

解决方案 »

  1.   

    public static Integer i = 0; //要使用对象类型才能同步,简单类型不支持
      

  2.   


    int i = 0;
    Integer i = 0;有什么区别吗
      

  3.   

    必须有前者i是一个基本数据类型,后者是一个对象。 楼主看下关于包装类这一章吧
    因为基本数据类型有时候在我们操作对象的时候不方便,于是就出现了包装类,就像你举的这个例子。
    synchronized括号里面,只能是对象,int i =0 这个i只是一个基本数据类型,我们为了使用i,那就必须让他变成对象,就必须用Integer i = 0;