java - Java中的多线程具有静态和非静态方法

标签 java multithreading static non-static

我一直在尝试 java 中多线程的不同行为。如果我在一个类中同时使用同步静态和非静态方法。 我的理解是,

-> 如果线程进入同步方法,线程将获取对象的锁,直到方法执行。

-> 如果线程进入静态同步方法,则线程获取类锁而不是对象锁。

真正混淆的部分是输出??。

    package com.threadImplementaion.examples;

class MyRunable implements Runnable
{
    public void run()
    {
        iterationMethod() ;
        staticIteration();
    }
    public synchronized void iterationMethod() 
    {
        //int count = 0  ;
        for(int i = 0 ; i < 5; i++ )
        {
            System.out.println( Thread.currentThread().getName() + " : " +  i);
        }
    }
    public  static synchronized  void staticIteration()
    {
        for(int i = 0 ; i < 10 ; i++ )
        {
            System.out.println(Thread.currentThread().getName() +  " static "  +  i);
        }
    }
}
public class MyRunnable 
{
    public static void main(String[] args) {
        Runnable runnable = new MyRunable() ;
        Thread thread1 = new Thread(runnable);
        thread1.start();
        thread1.setName("Thread1");
        Thread thread2 = new Thread(runnable) ;
        thread2.start();
        thread2.setName("Thread2") ;
        Thread thread3 = new Thread(runnable); 
        thread3.start();
        thread3.setName("Thread3");
        }


}



Output :
Thread1 : 0
Thread1 : 1
Thread1 : 2
Thread1 : 3
Thread1 : 4
Thread1 static 0
Thread1 static 1
Thread1 static 2
Thread1 static 3
Thread1 static 4
Thread1 static 5
**Thread1 static 6**
Thread3 : 0
Thread3 : 1
Thread3 : 2
Thread3 : 3
Thread3 : 4
Thread2 : 0
Thread2 : 1
Thread1 static 7
Thread2 : 2
Thread1 static 8
Thread2 : 3
Thread1 static 9
Thread2 : 4
Thread2 static 0
Thread2 static 1
Thread2 static 2
Thread2 static 3
Thread2 static 4
Thread2 static 5
Thread2 static 6
Thread2 static 7
Thread2 static 8
Thread2 static 9
Thread3 static 0
Thread3 static 1
Thread3 static 2
Thread3 static 3
Thread3 static 4
Thread3 static 5
Thread3 static 6
Thread3 static 7
Thread3 static 8
Thread3 static 9

最佳答案

同步的static 方法获得了Class 对象X 上的锁,该对象代表定义该方法的类。在这种情况下,synchronized 关键字原则上意味着仅在 static 方法之间进行同步。

而同步实例(非static)方法锁定调用该方法的当前对象Y

因此,同步的 static 方法和同步的实例方法仍然可以交错,因为它们锁定在两个不同的对象上。

关于java - Java中的多线程具有静态和非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31638295/

相关文章:

java - [Android]如何从字符串[]中获取项目编号(位置)

PHP 线程和高延迟文件访问(例如;FTP)

Android AsyncTask 和线程

java - 我无法理解的 ExceptionInInitializerError

java - 为什么我不能访问我的静态列表中的数据?

java - 更新了 eclipse、adt、Libgdx 无法在 android 上编译

java - 使用 Java 以电路形式模拟给定的 boolean 表达式

java - 在java中添加按钮来关闭应用程序是否合乎逻辑且正确?

java - 超时的完整 future 不起作用

c++ - 为什么在另一个头文件中声明结构会导致LNK2001错误?