小编Jav*_*per的帖子

当Integer对象用作同步块中的锁时,可能出现并发问题

在处理多线程程序时,我观察到了非常奇怪的行为.

当Integer对象用作锁时,似乎多个线程可以处于同步块中.甚至认为这是不可预期的.

如果我在下面的程序中使用任何其他静态成员,如's','o'和'c',则按预期工作.

码-

public class MyThread extends Thread{
    private static Integer ii=1;                        //Works fine
    private static Integer i=1;
    private static String s="1";                        //Works fine
    private static Object o= new Object();              //Works fine
    private static Class<MyThread> c= MyThread.class;   //Works fine

    public void run(){
        synchronized(i){
            System.out.print(i++ +" ");
            System.out.print(i+"   ");
        }
    }
    public static void main(String[] str) throws InterruptedException{
        for(int i=0;i<100;i++){
            MyThread t= new MyThread();
            t.start();
        }
        Thread.sleep(100);
        System.out.println();
        MyThread t= new MyThread();
        t.start();t.join();
        if(i!=102)
            System.out.println("fail");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出 -

2 …
Run Code Online (Sandbox Code Playgroud)

java multithreading

4
推荐指数
1
解决办法
145
查看次数

标签 统计

java ×1

multithreading ×1