小编Abh*_*pta的帖子

使对象同步后同步不起作用

我已经同步了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)

java multithreading

2
推荐指数
1
解决办法
49
查看次数

标签 统计

java ×1

multithreading ×1