Java Multi-Threading 17 issues

Source: Internet
Author: User
Tags thread class volatile

The Thread.Start () method (native) initiates the thread so that it enters a ready state, and the runtime executes the run () method when the CPU allocates time for the thread.

When you call the start () method, you will create a new thread and execute the code in the Run () method. But if you call the run () method directly, it does not create a new thread and does not execute code that invokes the thread.

2. 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.

3. 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

4. What happens when a thread runs out of an exception?

If the exception is not caught, the thread will stop executing. Thread.uncaughtexceptionhandler is an inline interface for dealing with abrupt interruptions of threads caused by uncaught exceptions. When an uncaught exception causes the thread to break, the JVM uses Thread.getuncaughtexceptionhandler () To query the thread's Uncaughtexceptionhandler and pass the thread and exception as arguments to the handler's Uncaughtexception () method for processing.

5, why wait, notify and notifyall These methods are not inside the thread class?

This is a design-related issue that examines the interviewer's view of the existing system and some common but seemingly irrational things. 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.

6. 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.

7. What is the difference between interrupted and Isinterruptedd methods in Java?

The main difference between interrupted () and isinterrupted () is that the former clears the interrupt state and the latter does not. The Java Multi-threading interrupt mechanism is implemented with an internal identity, and calling Thread.Interrupt () to break a thread sets the interrupt ID to true. when the interrupt thread calls the static mode thread.interrupted () to check the break state, the interrupt state is cleared by 0 . the non-static method, isinterrupted (), is used to query the interrupt state of other threads without changing the interrupt status identifier . Simply put, any method that throws a Interruptedexception exception will clear the interrupt state. In any case, the interrupt state of a thread can be changed by other threads calling interrupts.

8. 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.

9. 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.

10, how to write code to solve the problem of producer consumers?

The relatively low-level approach is to use wait and notify to solve the problem, the best way is to use semaphore or blockingqueue to achieve the producer consumer model.

11, how to avoid deadlocks?

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 and 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

12. 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.

13, 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.

14. 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.

15. 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.

16. 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.

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

This is an interesting question. 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.

Java Multi-Threading 17 issues

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.