简体   繁体   English

在Java中,如果两个类在同一时刻调用第三个类中的方法会发生什么?

[英]In Java what happens if two classes call a method in a third class at the same moment?

In my project I have a game class which is called by a client class. 在我的项目中,我有一个由客户端类调用的游戏类。 At the moment the game class writes a path to a file and the client class will read from this file and clear the contents. 目前,游戏类会写入文件的路径,客户端类将从此文件中读取并清除内容。 I am getting too many conflicts with access here so want to use another class as the method for storing the path data. 我在这里访问的冲突太多,所以想要使用另一个类作为存储路径数据的方法。 I want to know, however, if there will still be a problem, or what the outcome will be if the game class tries to call the method in the storage class to write whilst the client class at the same instant calls the method in the storage class to read and clear. 但是,我想知道,如果仍然存在问题,或者如果游戏类试图调用存储类中的方法进行写入,同时客户端类在同一时刻调用存储中的方法,结果会是什么课程阅读和清除。

Sounds like you need to think about threading and synchronization. 听起来你需要考虑线程和同步。 I'd recommend reading "Java Concurrency in Practice". 我建议阅读“Java Concurrency in Practice”。

In presence of multiple threads, your classes have to be thread safe . 在存在多个线程的情况下,您的类必须是线程安全的 One way of achieving this is to make the concurrently accessed methods synchronized . 实现此目的的一种方法是使同时访问的方法synchronized

Here is an example to get you started: 这是一个让你入门的例子:

public class Test {

    public static void main(String[] args) throws Exception {
        new Thread() { public void run() { Test.method(); }}.start();
        new Thread() { public void run() { Test.method(); }}.start();
    }

    public synchronized static void method() {
        System.out.println("hello ");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
        System.out.println("world");
    }
}

Without the synchronized modifier, this program would have printed 如果没有synchronized修饰符,则此程序将打印出来

hello 
hello    
world
world

With the synchronized keyword, only one thread at a time can call method , thus the program prints 使用 synchronized关键字,一次只能有一个线程调用method ,因此程序打印

hello 
world
hello 
world

I'm assuming your two classes are running in separate threads, so they might access the third class at the same time. 我假设你的两个类在不同的线程中运行,所以他们可能同时访问第三个类。 The access to the resource they are reading and writing needs to be synchronized (mutexed). 他们正在读取和写入的资源的访问需要同步(互斥)。 Java has the keyword "synchronized", which can be used in multiple ways to prevent concurrent modifications and such, see here and here for details Java有关键字“synchronized”,它可以以多种方式用于防止并发修改等,详见此处此处

The theoretically correct answer is: "anything can happen". 理论上正确的答案是:“任何事情都可能发生”。

The two calls can run one after the other or interleaved with each other, the results are unpredictable and potentially disastrous. 这两个调用可以一个接一个地运行,也可以相互交错,结果是不可预测的,可能是灾难性的。

That's why Java offers you several ways of dealing with it. 这就是为什么Java为您提供了几种处理它的方法。

  1. The simplest (sounding) way is to write your methods threadsafe. 最简单(听起来)的方法是编写方法线程安全。 In practice this usually means that you should only use local variables and must not modify the objects that are passed to you as parameters. 在实践中,这通常意味着您应该只使用局部变量,并且不得修改作为参数传递给您的对象。 (No side-effects.) Many methods automatically fall into this category, in which case you don't have to worry about concurrency. (没有副作用。)许多方法自动属于这一类,在这种情况下,您不必担心并发。

  2. If your method cannot be made threadsafe, you need to handle concurrent calls somehow. 如果你的方法不能成为线程安全的,你需要以某种方式处理并发调用。 synchronized blocks are the most often used constructs but in some cases, a volatile field or using Atomic* classes will suffice. synchronized块是最常用的构造,但在某些情况下, volatile字段或使用Atomic*类就足够了。 But this subject is way too heavy to be covered in a single answer, so I suggest you read the concurrency tutorial . 但是这个主题太重了,无法在一个答案中涵盖,所以我建议你阅读并发教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我们在Java中有两个具有相同名称的类时会发生什么? - what happens when we have two classes with same names in java? Java:具有主要方法的两个类访问相同的第三类 - Java: Two classes with main methods accessing the same third class 如何从java中的两个不同类调用相同的方法 - How to call same method from two different classes in java 当两个线程同时调用相同的静态方法时会发生什么? - What happens when two threads call the same static method at the same time? 如果两个Java框架需要第三个框架,但两个框架都需要不同版本的第三个框架,会发生什么情况? - What happens when two Java frameworks need third one but each of the two need different version of third one? 调用两个不同类的相同方法 - Call same method of two different classes 它们与第三个类相关联的两个类之间有什么关系? - What is the relationship between two classes they are tied to a Third class? 在Java中3个类中的另一个类中调用方法 - Call a method in another class within 3 classes in java 当少数线程尝试调用相同的同步方法时会发生什么? - What happens when few threads trying to call the same synchronized method? Java基类中超类的受保护方法会怎样? - What happens to protected method of a super class in base class in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM