[Liu Yang Java]_ selected 20 Java multi-threaded face questions

Source: Internet
Author: User
Tags finally block thread class visibility volatile

1. What are the pros and cons of multithreaded use?

Advantages:

(1) Multithreading technology makes the program response faster

(2) Tasks that are not currently being processed can give processor time to other tasks

(3) A task that takes up a lot of processing time can give the processor time to other tasks on a regular basis

(4) Can stop the task at any time

(5) Each task can be prioritized and optimized for performance

Disadvantages:

(1) Slow running of programs when waiting for shared resources

(2) Management of threads requires additional CPU overhead

(3) A thread deadlock condition may occur. Longer waits or resource competition, and deadlocks.

2. Introduction and differences between the start () method and the Run () method?

Start () Method:

1) Start the thread with the Start method and actually implement the multi-threaded operation, without waiting for the Run method body code to complete and proceed directly to execute the following code.

2) Start a thread by invoking the start () method of the thread class, at which point the thread is in a ready (operational) state and is not running, and once the CPU time slice is taken, the run () method is started.

Run () Method:

1) The Run () method is just a common method of the class, and if you call the Run method directly, there is still only one thread in the program, and the program execution path is only a single line.

Summarize:

1) Call the Start method to start the thread,

2) The Run method is just a normal method call to thread, or it executes in the main thread.

3) Place the code that needs to be processed in parallel in the run () method, and the start () method will automatically invoke the run () method, as specified by the JVM's memory mechanism.

4) and the run () method must be public access, the return value type is void

3. Runnable interface and callable interface of the same point and different points?

4. What is the role of the volatile keyword?

(1) Multithreading uses volatile keyword-modified variables to ensure its visibility between multithreading, that is, every time a volatile variable is read, it must be the latest data

(2) Java code execution, in order to get a better performance JVM may reorder the instructions, there may be some unexpected problems under multithreading. Using volatile will disable semantic reordering and, of course, reduce the efficiency of code execution to some extent

5. What is the difference between Cyclicbarrier and Countdownlatch?

6. Volatile vs. synchronized?

1) The volatile nature is to tell the JVM that the value of the current variable in the register is indeterminate and needs to be read from main memory, synchronized is locking the current variable, and the other threads are blocked only if the variable is accessible by the front-thread.

2) volatile can only be used at variable levels, synchronized can be used in variables, methods.

3) volatile can only realize the change visibility of variables, while synchronized can guarantee the change visibility and atomicity of variables.

4) volatile does not cause thread blocking, while synchronized may cause thread blocking

7. How to wake up a blocked thread?

If the thread is blocked by calling the wait (), sleep (), or join () method, it can be disconnected and wake it up by throwing interruptedexception, if the thread encounters io blocking, because IO is implemented by the operating system, Java code has no way of directly contacting the operating system

8. How do I get to the thread dump file in Java?

The purpose of the dump file:

Dead loop, deadlock, blocking, page open slow and so on, hitting thread dump is the best way to solve the problem. Therefore, thread dump is also the thread stack.

Gets the contents of the dump file to the thread stack in two steps:

(1) The first step: get to the thread of the Pid,linux environment can be used Ps-ef | grep java

(2) Step two: Print the thread stack, which can be done by using the Jstack PID command

9. The same and different points of the sleep method and the wait method?

Same point:

Both can leave the thread in a frozen state.

Different points:

1) First, it should be clear that the sleep method is the method defined in the thread class, and the wait method is the method defined in the object class.

2) The Sleep method must artificially specify the time for it.

The wait method can either specify a time or not specify a time.

3) Sleep method time, the thread is in a temporary blocking state or running state.

The wait method must be awakened by notify or notifyall if it has not been set for a time.

4) The Sleep method is not necessarily defined in synchronization.

The wait method must be defined in synchronization.

5) When both are defined in the synchronization,

The thread executes to sleep and does not release the lock.

The thread executes to wait and the lock is released

10. What is the role of producer and consumer models?

1) To improve the efficiency of the whole system by balancing producer's production capacity and consumer's consumption ability, which is the most important role of producer consumer model.

2) decoupling, which is the role of the producer consumer model, decoupling means that there is less contact between producers and consumers, the less contact the more can be developed independently without the need to receive mutual constraints

What is the role of threadlocal?

1) threadlocal is used to solve the concurrency problem of multi-thread

2) threadlocal is not a thread, but a local variable of thread, and when you use threadlocal to maintain a variable, threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently change its own copy , without affecting the replicas of other threads.

3) from the thread's point of view, the target variable is like a thread's local variable, which is the meaning of the "local" in the class name.

4) Thread Local variables are not a new Java invention, Java is not provided in language-level support (syntax), but rather in disguise through the Threadlocal class to provide support

What is the difference between the wait method and the Notify/notifyall method when discarding object monitor?

The wait () method immediately releases the object monitor;

The Notify ()/notifyall () method will wait for the thread's remaining code to finish before discarding the object monitor

What is the contrast between lock and synchronized?

1) lock is an interface, and synchronized is the key word in Java, synchronized is a built-in language implementation;

2) When an exception occurs, synchronized automatically releases the lock that the thread occupies, so it does not cause a deadlock, and in the event of an exception, lock is likely to cause a deadlock if it does not voluntarily release the lock through Unlock (). Therefore, lock must be released in the finally block when using lock;

3) lock allows the thread waiting for the lock to respond to interrupts, while synchronized does not, while using synchronized, the waiting thread waits and fails to respond to interrupts;

4) lock can be used to know if there is a successful acquisition of locks, and synchronized is unable to do.

5) lock can improve the efficiency of multiple threads for read operations.

6) in JDK1.5, synchronized is inefficient in performance. Because this is a heavyweight operation, the most significant impact on performance is a blocking implementation, and the operations of the suspend thread and the recovery thread need to be done in the kernel state, which can put a lot of pressure on the concurrency of the system. In contrast, using the lock object provided by Java provides a higher performance.

However, JDK1.6, has changed, to synchronize added a lot of optimization measures, there is adaptive spin, lock elimination, lock coarsening, lightweight lock, biased lock and so on. resulting in synchronize performance on JDK1.6 is no worse than lock. So. Priority is given to using synchronized to synchronize

14. What is the concurrency level of concurrenthashmap?

The concurrency of Concurrenthashmap is the size of segment, which defaults to 16, which means that up to 16 threads can operate concurrenthashmap at the same time. This is also the biggest advantage of Concurrenthashmap for Hashtable, and in any case, Hashtable can have two threads to get the data from Hashtable.

15. What is Readwritelock?

Readwritelock is a read-write lock interface, Reentrantreadwritelock is a specific implementation of the Readwritelock interface, the realization of the separation of Read and write, reading Lock is shared, the write lock is exclusive, read and read is not mutually exclusive, read and write, write and read, Writing and writing are mutually exclusive, improving the performance of Read and write

16. What is Futuretask?

Futuretask represents a task for an asynchronous operation. Futuretask inside can pass in a specific implementation class of callable, can wait for the result of the task of this asynchronous operation to obtain, judge whether has completed, cancels the task and so on operation. Because Futuretask is also an implementation class for the Runnable interface, Futuretask can also be placed in the thread pool

17. What is the thread scheduling algorithm used in Java?

Preemptive type. After a thread runs out of CPU, the operating system calculates a total priority based on data such as thread priority, thread starvation, and assigns the next time slice to a thread to execute

18. Thread safety in single-case mode?

The thread safety of a singleton pattern means that an instance of a class is created only once in a multithreaded environment. The singleton pattern has many kinds of writing, the specific analysis is as follows:

(1) How to a hungry man a single-case pattern: thread safety

(2) Lazy single-case pattern: Non-thread-safe

(3) Double lock single case pattern: thread safety

19, what is optimistic lock and pessimistic lock?

(1) Optimistic lock: Optimistic about the thread safety problem caused by the concurrency operation, optimistic lock that the competition does not always occur, so it does not need to hold the lock, will compare-set these two actions as an atomic operation to modify the memory variables, if the failure indicates a conflict, then there should be a corresponding retry logic.

(2) Pessimistic lock: The pessimistic state of the thread security problem caused by the concurrency operation, pessimism locks that the competition always occurs, so every time a resource is operated, it will hold an exclusive lock, like synchronized, which directly locks the operation resources.

Java writing a program that causes deadlocks?

Description of the deadlock phenomenon:

Thread A and thread B wait for each other to hold a lock that causes the program to loop indefinitely.

Steps to implement a deadlock:

(1) Two threads each hold two object objects: Lock1 and Lock2. These two locks act as the lock of the synchronous code block;

(2) Thread 1 of the Run () method in the synchronization code block first get Lock1 object lock, Thread.Sleep (XXX), time does not need too much, 100 milliseconds almost, and then get Lock2 object lock. This is done primarily to prevent thread 1 from starting all at once to obtain an object lock for the Lock1 and Lock2 two objects in a row

(3) thread 2 Run) (method in the synchronous code block first get Lock2 object lock, and then get Lock1 object Lock, of course, then Lock1 object lock has been held by thread 1 lock, thread 2 must be waiting for thread 1 to release Lock1 object lock

In this way, the thread 1″ sleep ", thread 2 has acquired the Lock2 object lock, thread 1 at this time to try to acquire Lock2 object lock, it is blocked, when a deadlock formed

The output is:

Thread A locks resource O1, waits for O2

Thread B Locks Resource O2, waits for O1

[Liu Yang Java]_ selected 20 Java multi-threaded face questions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.