ReentrantLock本身线程安全问题
 class Thread22 extends Thread {
    private String class_name = "";

    public Thread22(String classname) {
        class_name = classname;
    }

    public void run() {
        MyObjTest myobj = new MyObjTest();
        try {
            myobj.sayHello(true, class_name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread33 extends Thread {
    private String class_name = "";

    public Thread33(String classname) {
        class_name = classname;
    }

    public void run() {
        MyObjTest myobj = new MyObjTest();
        try {
            myobj.sayHello(false, class_name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


class MyObjTest {
    private static Integer count = new Integer(3);
    private Lock lock = new ReentrantLock();

    public void sayHello(boolean delete, String classname)
            throws InterruptedException {
        lock.lock();
        try { 
            if (delete && count == 3) {
                Thread.sleep(2000);
                count--;
                System.out.println("Thread:" + classname + "| count: " + count);
            } else {
                count++;
                System.out.println("Thread:" + classname + "| else count: "
                        + count);
            }
        }
        finally {
          lock.unlock(); 
        }
    }

    public void sayHello_sync(boolean delete, String classname)
        throws InterruptedException {
        synchronized (count) {
            if (delete && count == 3) {
                Thread.sleep(2000);
                count--;
                System.out.println("Thread:" + classname + "| count: " + count);
            } else {
                count++;
                System.out.println("Thread:" + classname + "| else count: "
                        + count);
            }
        }
    }
}

public class ThreadSafeTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Thread22 t2 = new Thread22("t2");
        Thread33 t3 = new Thread33("t3");
        Thread33 t31 = new Thread33("t31");
        Thread33 t32 = new Thread33("t32");
        t2.start();
        t3.start();
        t31.start();
        t32.start();
    }

}

经测试ReentrantLock是没有起作用的,线程同时进入了受保护的代码。但将lock修改为静态的则解决是可以的:
private static Lock lock = new ReentrantLock();

那我就奇怪了,ReentrantLock()本身就是普通的类,如果在多个线程间使用时,也必须是唯一的实例才行?这样的话设计出来是不是有问题呢?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!