Java的线程问题互锁问题

我创建了两个线程,共同请求两个资源 Object1 和 Object2。线程1占用O1然后请求
O2;同理 线程2 占用 O2 请求 O1,为了防止线程一下子走完从而没有一直保持占用资源的状态,我还添加了一个倒计时。

可是当线程2明显占用了资源2的时候,线程1还是能够获取到资源2.请问这是为什么呢?

public class DeadLockThreadDemo {

    // 定义两个资源
    public static Object resource01 = new Object();
    public static Object resource02 = new Object();

    public static void main(String[] args) {
        /*ExecutorService executorService = Executors
                .newFixedThreadPool(3, new MyThreadFactory("Gary Thread pool"));
        executorService.execute(new TakeResource1(resource01, resource02));
        executorService.execute(new TakeResource2(resource01, resource02));*/
        Thread thread1 = new Thread(new TakeResource1(resource01, resource02));
        Thread thread2 = new Thread(new TakeResource2(resource01, resource02));
        thread1.start();
        thread2.start();
    }
}

class TakeResource1 implements Runnable{

    final Object resource1;
    final Object resource2;
    public TakeResource1(Object resource1, Object resource2) {
        this.resource1 = resource1.toString();
        this.resource2 = resource2.toString();
    }

    @Override
    public void run() {

        synchronized (resource1)
        {
            System.out.println("线程" + Thread.currentThread().getName() + " 占用资源 " + resource1 + " 请求 " +resource2 + " 线程状态:" + Thread.currentThread().getState());

            synchronized (resource2) {
                System.out.println("线程" + Thread.currentThread().getName() + " 成功占用 " + resource2);
            }
        }
    }
}

class TakeResource2 implements Runnable{

    final Object resource1;
    final Object resource2;
    public TakeResource2(Object resource1, Object resource2) {
        this.resource1 = resource1.toString();
        this.resource2 = resource2.toString();
    }

    @Override
    public void run() {
        synchronized (resource2)
        {
            System.out.println("线程" + Thread.currentThread().getName()  + " 占用资源 " + resource2 + " 请求 " + resource1);

            try {
                for (int i = 10; i > 0; i--) {
                    System.out.println(Thread.currentThread().getName() + " 线程占用了" + resource2 + " 开始休眠:" + i);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (resource1) {
                System.out.println("线程" + Thread.currentThread().getName() + " 成功占用 " + resource1);

            }
        }
    }
}

图片说明

3个回答

加锁需要使用同一个实例

加速应该用单列模式去加。

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