java - 锁定java同步方法

标签 java multithreading synchronization synchronized

我正在尝试使用同步方法编写一个带有线程的 Java 程序。但是我无法理解当另一个线程调用 java 中的同步方法时,我如何显示一个线程已经在运行。谁能用简单的例子解释一下

最佳答案

这是一个人为的例子,它显示了交织和阻塞过程。在我的机器上打印:

Thread[Thread-0,5,main] is going to call the synchronized method
Thread[Thread-1,5,main] is going to call the synchronized method
Thread[Thread-0,5,main] is in the synchronized method
Thread[Thread-0,5,main] is exiting the method
Thread[Thread-1,5,main] is in the synchronized method
Thread[Thread-1,5,main] is exiting the method

可以看到只有一个线程进入了同步块(synchronized block),而另一个在等待。

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");
    }
}

关于java - 锁定java同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13796961/

相关文章:

java - 为什么 Netbeans 看不到我指的是哪个 varargs 方法?

multithreading - Azure XS 虚拟机上不带 GUI 的 Ubuntu 服务器

java - 多个线程之间共享和锁定固定数量的资源

c# - 使用字符串作为锁来做线程同步

java - 正确同步在主线程中创建并传递给新线程的 map 对象

JAVA\仅在运行时编译一个函数

java - maven:构建期间的版本冲突

java - 类作为 Android 应用程序的弹出窗口

android - 改变方向的工作流程

spring-boot - kubernetes hazelcast 错误仅在一个命名空间中同步