How do I make Java wait for a method to finish before continuing?

前端 未结 2 1949
不思量自难忘°
不思量自难忘° 2021-01-21 09:24

So my problem is that I need these methods to run one after another but I cannot work out how to make the methods wait before being run. Any help is appreciated. Thank you. Here

2条回答
  •  自闭症患者
    2021-01-21 09:55

    The easiest solution might be to not use threads, but i doubt that is what you want.

    What you might be looking for is the concept of locks:

    A method may acquire the lock associated with an object by calling:

    synchronized(nameOfTheLockObject) {
        //do some code here
    }
    

    This acquires the lock of the given Object, executes the code and releases the lock afterwards. If the lock is already acquired by another method/thread, the code pauses until the lock is released by the other method/thread.

    You can also add the synchronized statement to methods of a class to make them acquire the lock of the parent object.

    More Information on this is given at: http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

提交回复
热议问题