Java Interview FAQ - thread section (with answers)

java There are several ways to implement a thread? What keywords synchronization method modified? Stop () and suspend () method Why not recommended?

A: There are two methods, namely, inheritance Thread class and Runnable interface to achieve
synchronization with the synchronized keyword modified method
against the use of stop (), because it is not safe, suspend () method prone to deadlock.

sleep () and wait () What is the difference?

A: sleep is a method of the Thread class (Thread), leading to this thread to suspend the specified time, the opportunity to perform to the other thread, but monitoring status remains, to the post will be automatically restored. Call sleep will not release the object lock.
wait is a method of the Object class, object calls this method leads to wait this thread to give the object lock, waiting to enter the pool waiting for a lock for this object, and only issued after notify method (or notifyAll) this thread for this object was to obtain the object lock into operation .

Similarities and differences between synchronous and asynchronous, under what circumstances were they to use? for example.

A: If data will be shared between threads. For example, may be read by another thread after the writing of data, or data is being read may have been written by another thread, then the data is shared data, access must be synchronized.
When the application calls the method takes a long time to execute on the object, and do not want the program to wait for the process to return, you should use asynchronous programming, using asynchronous approach in many cases tend to be more efficient.

Start a thread is run () or start ()?

A: Start a thread that calls start () method, the thread is represented by the virtual processor can run the state, which means that it can schedule and execute by the JVM. This does not mean that the thread will run immediately. run () method can produce signs must quit to stop a thread.

When a thread enters a synchronized method of an object, other threads can access this object other methods?

A: No, an object of a synchronized method can only be accessed by a thread.

Please tell thread synchronization method you know.

答:wait()、sleep()、notify()、Allnotity()、synchronized,

Description of the similarities and differences between synchronized and java.util.concurrent.locks.Lock?

A: The main similarities: Lock to complete all the functions synchronized achieved
major differences: Lock more accurate than synchronized thread semantics and better performance. synchronized automatically release the lock, and Lock requires the programmer must manually released and must be released in the finally clause.

NOTE: For detailed tutorial thread: https: //blog.csdn.net/Smile_Sunny521/article/details/89704158

Published 114 original articles · won praise 52 · views 20000 +

Guess you like

Origin blog.csdn.net/Smile_Sunny521/article/details/101269192