[英]locks on java synchronized methods
I am trying to write a java program with threads using synchronized methods. 我正在尝试使用同步方法编写带有线程的java程序。 But iam not able to understand how can i display that already a thread is running when another thread invokes synchronized method in java.
但是当我在另一个线程调用java中的synchronized方法时,我无法理解如何显示已经运行的线程。 Can any one explain with simple example
任何人都可以用简单的例子来解释
Here is a contrived example which shows the interleaving and blocking process. 这是一个设计的例子,它显示了交错和阻塞过程。 On my machine it prints:
在我的机器上打印:
Thread[Thread-0,5,main] is going to call the synchronized method
Thread [Thread-0,5,main]将调用synchronized方法
Thread[Thread-1,5,main] is going to call the synchronized methodThread [Thread-1,5,main]将调用synchronized方法
Thread[Thread-0,5,main] is in the synchronized methodThread [Thread-0,5,main]在synchronized方法中
Thread[Thread-0,5,main] is exiting the methodThread [Thread-0,5,main]正在退出该方法
Thread[Thread-1,5,main] is in the synchronized methodThread [Thread-1,5,main]在synchronized方法中
Thread[Thread-1,5,main] is exiting the method线程[Thread-1,5,main]正在退出该方法
You can see that only one thread enters the synchronized block while the other waits. 您可以看到只有一个线程进入同步块而另一个线程等待。
public class Test1 {
public static void main(String[] args) throws Exception {
final Test1 test = new Test1();
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread() + " is going to call the synchronized method");
test.method();
}
};
new Thread(r).start();
new Thread(r).start();
}
public synchronized void method() {
System.out.println(Thread.currentThread() + " is in the synchronized method");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
System.out.println(Thread.currentThread() + " is exiting the method");
}
}
If I understand you correctly you want to print a message when a thread tries to invoke a synchronized method while another thread is already executing it. 如果我理解正确,当线程试图调用同步方法而另一个线程已经在执行它时,你想要打印一条消息。 You cannot do this with synchronized methods or blocks but you can do it using java.util.concurrent.locks.Lock interface instead.
您无法使用同步方法或块执行此操作,但您可以使用java.util.concurrent.locks.Lock接口来执行此操作。 The method you need is tryLock().
您需要的方法是tryLock()。 You can do something like this:
你可以这样做:
public class Test1 {
private Lock lock = new ReentrantLock();
// ...
public void method() {
if (lock.tryLock()) {
try {
// you successfully acquired the lock, do you logic here
} finally {
lock.unlock();
}
} else {
// lock is hold by another thread
System.out.println("cannot acquire a lock");
}
}
}
You can easily evolve this example to print which thread exactly holds the lock if you wish. 如果您愿意,您可以轻松地演变此示例以打印哪个线程完全保持锁定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.