java:reentrantlock不起作用-它仍然相互混合

db2dz4w8  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(461)

我不明白为什么代码不能正常工作。这些线还在互相混合。
我有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();
    }
}

这是输出:

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

mzsu5hc0

mzsu5hc01#

这个 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();
        }
    }
}

相关问题