Frequently-used face questions about multithreading!

Source: Internet
Author: User

1. What is a thread?

A thread is the smallest unit that the operating system can perform operations on, which is included in the process and is the actual operating unit of the process. Programmers can use it for multiprocessor programming, and you can speed up operations-intensive tasks using multithreading. For example, if a thread takes 100 milliseconds to complete a task, it takes 10 milliseconds to complete the task with 10 threads.

2. What is the difference between threads and processes?

1) threads are a subset of processes, a process has at least 1 threads, and each thread performs different tasks in parallel.

2) Different processes use different memory spaces, and all threads share the same amount of memory space.

3) Each thread has a separate stack memory to store local data.

3. How do I implement threads in Java?

Usually 80% of the answer is two ways to inherit the thread class and implement the Runnable interface, but if you want to add points, the implementation of the callable interface and use the thread pool, so the best answer to the interview is to answer these 4 ways.

4, with runnable or thread?

It is better to implement the runnable interface than to inherit the thread:

1) Suitable for multiple threads sharing the same resource

2) Avoid the limitations of single inheritance

3) detach and decouple the thread task from the thread object to increase the robustness of the program

4) Only runnable can be used in the thread pool callable

5. What is the difference between the start () and run () methods in the Thread class?

The start () method is used to start the newly created thread, and start () calls the run () method internally, which is not the same as calling the run () method directly. When you call the run () method, only the original thread is called, no new thread is started, and the start () method starts the new thread.

6. What is the difference between runnable and callable in Java?

Both runnable and callable represent tasks that you want to perform in different threads. Runnable from the JDK1.0 began, callable is in the JDK1.5 increase. The main difference is that the callable call () method can return a value and throw an exception, while the runnable run () method does not have these features. The callable can return a future object loaded with calculated results.

7. What are the volatile variables in Java?

Volatile is a special modifier that can only be used by member variables. Multithreaded operations on member variables are transparent to other threads in the absence of a synchronization class for Java concurrency programs. The volatile variable guarantees that the next read operation will occur after the previous write operation.

8. What is thread safety? is vector a thread-safe class?

If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe. The same instance object of a thread-safe counter class will not have a computational error if it is used by multiple threads. Obviously you can divide the collection classes into two groups, thread-safe and non-thread-safe. Vectors are thread-safe with synchronous methods, and ArrayList similar to it are not thread-safe.

9. How do I stop a thread in Java?

Java provides a rich API but does not provide an API for stopping threads. JDK 1.0 originally had some control methods like Stop (), suspend (), and resume () but because of the potential deadlock threat they were deprecated in subsequent JDK versions, the Java API designers did not provide a compatible and thread-safe way to stop a thread. When the run () or call () method finishes executing, the thread ends automatically, and if you want to end a thread manually, you can use the volatile Boolean variable to exit the run () method's loop or cancel the task to break thread.

10, how to share data between two threads?

1) If each thread executes the same code, the same Runnable object can be used, and the Runnable object has that shared data, for example, a ticket-selling system can do so.

2) If each thread executes a different code, it is time to use a different runnable object, for example, to design 4 threads. Of these, two threads add 1 to J at a time, and two threads to J each minus 1, bank deposit and withdrawal

There are two ways to solve this type of problem:

The shared data is encapsulated into another object, which is then passed to each Runnable object one by one, and each thread assigns the method of the shared data to that object, which makes it easy to implement mutual exclusion and communication for each operation of the data.

Use the Runnable object as the inner class of a class, share the data as a member variable of this class, and each thread also encapsulates the external class for the operation method of the shared data, in order to achieve synchronization and mutual exclusion for each operation of the data, and to invoke these methods of the outer classes as individual runnable objects of the inner class

11. What is the difference between notify and Notifyall in Java?

The Notify () method does not wake up a specific thread, so only one thread waits for it to be useful. Notifyall () Wakes all threads and allows them to scramble for locks to ensure that at least one thread can continue to run.

12, Why wait, notify and notifyall These methods are not inside the thread class?

To answer these questions, you need to explain why it makes sense to put these methods in the object class, and why not put them in the thread class. One obvious reason is that the locks provided by Java are object-level rather than thread-level, and each object has a lock, which is obtained through the thread. The wait () method in the calling object is meaningful if the thread waits for some locks. If the wait () method is defined in the thread class, it is not obvious which lock the thread is waiting for. Simply put, because Wait,notify and Notifyall are both lock-level operations, they are defined in the object class because the locks belong to the objects.

13. What is a threadlocal variable?

Threadlocal is a special variable in Java. Each thread has a threadlocal that each thread has its own independent variable, and the race condition is completely eliminated. It is a good way to get thread-safe for creating expensive objects, such as you can use threadlocal to make SimpleDateFormat thread-safe, because that class is expensive to create and each call needs to create a different instance, so it's not worth using it in a local scope. If you provide a copy of your own unique variables for each thread, you will be much more efficient. First, it reduces the number of expensive objects created by multiplexing. Second, you get thread safety without using high-cost synchronization or immutability. Another good example of thread-local variables is the Threadlocalrandom class, which reduces the number of expensive random objects created in a multithreaded environment.

14. What is Futuretask?

In a Java concurrency program, Futuretask represents an asynchronous operation that can be canceled. It has the methods of starting and canceling operation, whether the query operation is complete and retrieving the result of operation. The result can be retrieved only when the operation is complete, and the Get method will block if the operation has not been completed. A Futuretask object can be wrapped on an object that calls callable and runnable, because Futuretask also calls the Runnable interface so it can be submitted to executor for execution.

15. Why wait and notify methods are called in the synchronization block?

The main reason is that the Java API enforces this, and if you don't, your code throws a Illegalmonitorstateexception exception. Another reason is to avoid a race condition between wait and notify.

16. Why should you check the waiting conditions in the loop?

A thread that is in a wait state may receive an error alert and a pseudo-wake, and if the wait condition is not checked in the loop, the program exits without satisfying the end condition. Therefore, when a waiting thread wakes up, it cannot assume that its original wait state is still valid, and it may change after the Notify () method call and before the waiting thread wakes up. That's why using the Wait () method in a loop works better, so you can create a template in Eclipse and call wait and notify.

17. What is the difference between synchronous collections in Java and concurrent collections?

Both synchronous and concurrent collections provide the appropriate thread-safe collection for multithreading and concurrency, although the concurrency collection is more extensible. Before Java1.5, programmers had only synchronized sets to use and in the multi-threaded concurrency will lead to contention, hindering the system's extensibility. JAVA5 introduces concurrent collections like Concurrenthashmap, which not only provides thread safety but also improves scalability with modern technologies such as lock separation and internal partitioning.

18. What is the difference between heap and stack in Java?

Why is this problem categorized in multi-threaded and concurrent-facing questions? Because the stack is an area of memory that is closely related to threads. Each thread has its own stack memory, which is used to store local variables, method parameters, and stack calls, and variables stored in one thread are not visible to other threads. The heap is a common area of memory shared by all threads. Objects are created in the heap, in order to increase the efficiency of the thread will get a cache from the heap to its own stack, if multiple threads use the variable can cause problems, then the volatile variable can play a role, it requires the thread to read the value of the variable from main memory.

19. What is a thread pool? Why use it?

Creating threads takes expensive resources and time, and if the task is to create a thread, the response time is longer and the number of threads a process can create is limited. To avoid these problems, when the program starts, it creates several threads that respond to processing, called the thread pool, which is called a worker thread. Starting with JDK1.5, the Java API provides a executor framework that allows you to create different thread pools. For example, a single thread pool, one task at a time, a fixed number of thread pools or a pool of cache threads (an extensible thread pool for programs that are suitable for many short-lived tasks).

20, how to avoid deadlocks?

Deadlock in Java Multi-threading

Deadlock refers to two or more processes in the process of execution, because of the competition for resources caused by a mutual waiting phenomenon, if there is no external force, they will not go forward. This is a serious problem because a deadlock will cause your program to hang and cannot complete the task, the following four conditions must be met for a deadlock to occur:

· Mutex condition: A resource can only be used by one process at a time.

· Request and hold condition: When a process is blocked by a request for resources, it remains in place for the resources that have been obtained.

· Non-deprivation: the resources that the process has acquired cannot be forcibly stripped until the end of use.

· Cyclic wait condition: a cyclic waiting resource relationship is formed between several processes.

The simplest way to avoid deadlocks is to stop the loop waiting condition, set the flags, sort all the resources in the system, and stipulate that all process request resources must operate in a certain order (ascending or descending) to avoid deadlocks.

21. What is the difference between a live lock and a deadlock in Java?

A live lock is similar to a deadlock, except that the state of a thread or process in a live lock is constantly changing, and a live lock can be considered a special hunger. A realistic example of a live lock is two people in a narrow corridor, two people are trying to avoid each other to allow each other to pass, but because the direction of avoidance is the same result in the end no one can pass the corridor. Simply put, the main difference between a live lock and a deadlock is that the state of the former process can be changed but cannot continue to execute.

22, how to detect whether a thread has a lock?

In Java.lang.Thread there is a method called Holdslock (), which returns true if and only if the thread has a lock on a specific object.

23. How do you get the thread stack in Java?

There are several ways to get the thread stack for a Java process for different operating systems. When you get the thread stack, the JVM either saves the state of all the threads to the log file or outputs it to the console. In Windows you can use the CTRL + BREAK key combination to get the thread stack, Linux under the kill-3 command. You can also use the Jstack tool to get it, which operates on the thread ID and you can find the ID using the JPS tool.

24. Which parameter in the JVM is the small stack stack used to control thread

The problem is simple, and the-XSS parameter is used to control the stack size of the thread.

25. What is the difference between synchronized and Reentrantlock in Java?

Java has had some drawbacks in the past for a long time only through the Synchronized keyword to achieve mutual exclusion. For example, you cannot extend a method or block boundary outside of a lock, and you cannot cancel it while trying to acquire a lock. Java 5 provides more complex control through the lock interface to address these issues. The Reentrantlock class implements Lock, which has the same concurrency and memory semantics as synchronized, and it also has extensibility.

26, there are three threads t1,t2,t3, how to ensure that they are executed sequentially?

There are several ways to get threads to execute in a particular order in multiple threads, and you can use the join () method of the thread class to start another thread in one thread, and another thread to finish the thread. In order to ensure the order of three threads you should start the last one (T3 call t2,t2 call T1) so T1 will be completed first and T3 finalized.

27. How does the yield method in the thread class work?

The yield method can pause the currently executing thread object, allowing other threads with the same priority to execute. It is a static method and only guarantees that the current thread abandons the CPU and does not guarantee that other threads will be able to occupy the CPU, and that the thread executing yield () is likely to be executed immediately after entering the paused state.

28. What is the concurrency level of concurrenthashmap in Java?

Concurrenthashmap the actual map into several parts to achieve its extensibility and thread safety. This partitioning is obtained using concurrency, which is an optional parameter to the Concurrenthashmap class constructor, with a default value of 16, which avoids contention in multithreaded situations.

29. What is semaphore in Java?

Semaphore in Java is a new synchronization class, which is a counting signal. Conceptually, the semaphore maintains a set of permissions in a conceptual sense. If necessary, block each acquire () before the license is available, and then obtain the license. Each release () adds a license that may release a blocked fetch. However, instead of using the actual license object, semaphore only counts the number of available licenses and takes action accordingly. Semaphores are often used in multithreaded code, such as database connection pooling.

30. If you submit a task, the thread pool queue is full. What will happen when the meeting is made?

This question is tricky to ask, and many programmers think the task will block until the thread pool queue is empty. In fact, if a task cannot be scheduled to execute, then the Threadpoolexecutor's submit () method throws a Rejectedexecutionexception exception.

31. What is the difference between the submit () and execute () methods in the Java thread pool?

Two methods can submit a task to the thread pool, the return type of the Execute () method is void, it is defined in the executor interface, and the Submit () method can return a future object holding the result of the calculation, which is defined in the Executorservice interface. It extends the executor interface, and other thread pool classes like Threadpoolexecutor and Scheduledthreadpoolexecutor have these methods.

32. What is Readwritelock in Java?

Generally speaking, read-write locks are the result of lock separation techniques used to improve concurrent program performance. Readwritelock in Java is a new interface in Java 5, a readwritelock maintains a pair of associated locks, one for read-only operations and one for writing. In the absence of a write thread, a read lock may be held by multiple read threads at the same time. Write locks are exclusive, and you can use the Reentrantreadwritelock in the JDK to implement this rule, which supports up to 65,535 write locks and 65,535 read locks.

33. What is a busy loop in multi-threading?

A busy loop is when a programmer uses a loop to wait for a thread, unlike the traditional method wait (), sleep () or yield (), which discards CPU control, and the busy loop does not abandon the CPU, it is running an empty loop. The purpose of this is to preserve the CPU cache, in which a waiting thread wakes up in a multi-core system and may run in another kernel, which rebuilds the cache. It can be used to avoid rebuilding the cache and reducing the time it takes to wait for a rebuild.

34. What is the difference between volatile variables and atomic variables?

First, the volatile variable and the atomic variable look alike, but the function is different. Volatile variables ensure that the antecedent relationship, that is, the write operation occurs before subsequent reads, but it does not guarantee atomicity. For example, if you modify the count variable with volatile, then the count++ operation is not atomic. The atomic method provided by the Atomicinteger class allows this operation to be atomic, such as the Getandincrement () method, which atomically increments the current value by one, and other data types and reference variables can be similarly manipulated.

35. How to create thread-safe singleton in Java?

You can use the class load and static variable initialization features of the JVM to create a singleton instance, or use an enumeration type to create a singleton.

Frequently-used face questions about multithreading!

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.