【发布时间】:2015-07-29 21:25:18
【问题描述】:
我正在尝试了解 ReentrantLock 在 Java 中的内部工作原理。
我已经创建了一个示例:-
package com.thread.trylock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockingDemo {
final Lock lock = new ReentrantLock();
public static void main(final String... args) {
new ReentrantLockingDemo().go();
}
private void go() {
Runnable run1 = newRunable();
Thread t1 = new Thread(run1, "Thread1");
System.out.println(run1.hashCode());
t1.start();
Runnable run2 = newRunable();
Thread t2 = new Thread(run2, "Thread2");
System.out.println(run2.hashCode());
t2.start();
}
private Runnable newRunable() {
return new Runnable() {
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public void run() {
do {
try {
if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
try {
System.out.println("locked thread "
+ Thread.currentThread().getName());
Thread.sleep(1000);
} finally {
lock.unlock();
System.out.println("unlocked locked thread "
+ Thread.currentThread().getName());
}
break;
} else {
System.out.println("unable to lock thread "
+ Thread.currentThread().getName()
+ " will re try again");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);
}
};
}
}
//Output something like this (which may be slightly different on your machine)
locked thread Thread2
unable to lock thread Thread1 will re try again
locked thread Thread1
unlocked locked thread Thread2
unlocked locked thread Thread1
现在我的问题是有 2 个线程对象和 2 个可运行对象和 2 个线程。每个线程都应该在自己的堆栈帧上为不同的可运行对象运行 run 方法。如果每个线程使用不同的可运行对象在堆栈上运行自己的运行方法,则输出应该不同。
我见过一些例子,我们创建了几个线程,我们将一个共享对象传递给这些线程,我们在该共享对象的方法中进行锁定和解锁。这里的对象是不共享的。有 2 个可运行对象传递给 2 个线程对象,但可运行对象表现为共享对象。
您能否解释一下可能导致此输出的原因?或者可以提供一些澄清
谢谢
【问题讨论】:
标签: java multithreading