【问题标题】:Java : ReentrantLock doesn't work It still mixing with each otherJava:ReentrantLock 不起作用它仍然相互混合
【发布时间】:2020-11-20 13:31:09
【问题描述】:

我不明白为什么代码不能正常工作。线程仍然相互混合。

我有 A 类:

package com.company;

public class A implements Runnable {
    ReentrantLockClass r;

    public A(ReentrantLockClass r) {
        this.r = r;
    }

    @Override
    public void run() {
        r.print(5);
    }
}

和 B 类:

package com.company;

public class B implements Runnable{
    ReentrantLockClass r;

    public B(ReentrantLockClass r) {
        this.r = r;
    }

    @Override
    public void run() {
        r.print(10);
    }
}

这是用于运行 ReentrantLock 的 ReentrantLockClass

package com.company;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockClass {
    public void print(int count){
        ReentrantLock lock = new ReentrantLock();
        try {
            lock.lock();
            for(int i = 1 ; i <= 10 ; i ++){
                System.out.println(count * i);
                Thread.sleep(500);
            }
        }
        catch (Exception e){}
        finally {
           lock.unlock();
        }
    }
}

这是主类:

package com.company;

public class Main {

    public static void main(String[] args) {
        ReentrantLockClass r = new ReentrantLockClass();

        A a = new A(r);
        B b = new B(r);

        Thread t1 = new Thread(a);
        Thread t2 = new Thread(b);

        t1.start();
        t2.start();
    }
}

这是输出:

它应该运行一个线程然后运行其他线程

【问题讨论】:

  • print 类中的 ReentrantLockClass 方法在每次调用时都会创建自己的 ReentrantLock 实例。所以A和B调用的时候,有两个独立的锁,当然不会互相等待。在ReentrantLockClass 中创建一个ReentrantLock 实例作为成员变量,而不是每次都在print 方法中创建它。

标签: java multithreading oop locking reentrantlock


【解决方案1】:

print 方法创建一个新的ReentrantLock 实例。因此,每个线程都会锁定自己的锁,因此它们不会相互阻塞。一种方法是在 ReentrantLockClass'(隐式)构造函数中创建锁,然后在 print 方法中将其锁定:

public class ReentrantLockClass {
    // One lock shared for the instance
    ReentrantLock lock = new ReentrantLock();

    public void print(int count){
        try {
            lock.lock();
            for(int i = 1 ; i <= 10 ; i ++){
                System.out.println(count * i);
                Thread.sleep(500);
            }
        }
        catch (Exception e){}
        finally {
           lock.unlock();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    相关资源
    最近更新 更多