我不明白为什么代码不能正常工作。这些线还在互相混合。
我有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();
}
}
这是输出:
它应该先运行一个线程,然后再运行其他线程
1条答案
按热度按时间mzsu5hc01#
这个
print
方法创建新的ReentrantLock
示例。因此,每个线程都锁定自己的锁,因此它们不会相互阻塞。一种方法是在ReentrantLockClass
'(隐式)构造函数,然后将其锁定在print
方法: