同一类

时间:2016-10-10 17:52:24

标签: java multithreading

我有一个班级c,其中包含3个同步功能m1m2m3。我创建了同一个类c1c2c3的3个不同实例,每个实例分别在不同的线程t1t2t3上运行。如果t1访问权限m1可以t2t3访问m1 ??

1 个答案:

答案 0 :(得分:1)

取决于。如果方法是静态的,那么它们在类对象上同步并且交错是不可能的。如果它们是非静态的,那么它们在this - 对象上同步并且可以进行交错。以下示例应阐明行为。

import java.util.ArrayList;
import java.util.List;

class Main {
  public static void main(String... args) {
    List<Thread> threads = new ArrayList<Thread>();

    System.out.println("----- First Test, static method -----");
    for (int i = 0; i < 4; ++i) {
      threads.add(new Thread(() -> {
        Main.m1();
      }));
    }
    for (Thread t : threads) {
      t.start();
    }
    for (Thread t : threads) {
      try {
        t.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    System.out.println("----- Second Test, non-static method -----");
    threads.clear();
    for (int i = 0; i < 4; ++i) {
      threads.add(new Thread(() -> {
        new Main().m2();
      }));
    }
    for (Thread t : threads) {
      t.start();
    }
    for (Thread t : threads) {
      try {
        t.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    System.out.println("----- Third Test, non-static method, same object -----");
    threads.clear();
    final Main m = new Main();
    for (int i = 0; i < 4; ++i) {
      threads.add(new Thread(() -> {
        m.m2();
      }));
    }
    for (Thread t : threads) {
      t.start();
    }
    for (Thread t : threads) {
      try {
        t.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public static synchronized void m1() {
    System.out.println(Thread.currentThread() + ": starting.");
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(Thread.currentThread() + ": stopping.");
  }

  public synchronized void m2() {
    System.out.println(Thread.currentThread() + ": starting.");
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(Thread.currentThread() + ": stopping.");
  }
}

有关详细信息,请参阅this oracle page