我已经同步了Integer对象a,我期待输出1 2 3 4 5 6 7 8 9但是它仍然给我其他输出.问题是因为我已经同步了每个线程试图访问的变量.
package thread;
public class BasicThread extends Thread {
static Integer a=new Integer(0);
void incr() {
synchronized (a) {
a++;
System.out.println(a);
}
}
public void run() {
incr();
incr();
incr();
}
public static void main(String[] args) throws InterruptedException {
BasicThread bt=new BasicThread();
BasicThread bt1=new BasicThread();
BasicThread bt2=new BasicThread();
bt.start();
bt1.start();
bt2.start();
}
}
Run Code Online (Sandbox Code Playgroud)