Threading in Java: How to lock an object?

前端 未结 7 734
长发绾君心
长发绾君心 2020-12-29 03:33

The following Function is executing in its own thread:

private void doSendData()
{
    try {

           //writeToFile(); // just a temporary location of a c         


        
7条回答
  •  没有蜡笔的小新
    2020-12-29 04:31

    The above are correct. You can use a synchronized block of code. Or you can create what they call a mutex. A mutex can actually be any object. Lots of people just use Object itself as a mutex. Then you can lock on the mutex. Any threads wanting to get access must wait for thread holding the mutex to release it.

    There was also a suggestion by Apocalisp. I would also recommend that you look at the java.util.concurrent package.

提交回复
热议问题