Multithreading in Java programmer interviews

Source: Internet
Author: User
Tags ibm developerworks

Many core Java interview questions come from multi-threading and collection framework. skillful practical experience is required to understand the concept of core threads. This article collects typical Java thread problems that are frequently asked by senior engineers.

0. What is multithreading synchronization in Java?

In a multi-threaded program, synchronization can control access to shared resources. If there is no synchronization, when a Java thread modifies a shared variable, another thread is using or updating the same variable, which may easily lead to program errors.

1. How can I implement multithreading?

A Java thread can implement the runnable interface or inherit the Thread class. When you plan to implement multiple inheritance, the runnable is preferred.

2. What is the difference between thread. Start () and thread. Run?

The thread. Start () method (native) starts the thread and enters the ready state. When the CPU allocates time for this thread, the JVM schedules the run () method.

3. Why do we need the run () and start () Methods? Can we use the run () method to complete the task?

We need the run () & START () methods because the JVM creates a separate thread, which is different from the call of a common method. Therefore, this work is done by the START method of the thread, start is implemented by local methods and needs to be displayed and called. Another advantage of using these two methods is that any object can be run as a thread, as long as the runnable interface is implemented, this avoids the Java multi-Inheritance Problem Caused by inheriting the Thread class.

4. What is the threadlocal class and how to use it?

Threadlocal is a local variable at the Thread level, not a "local thread ". Threadlocal provides an independent copy of the variable for each thread that uses the variable. Modifying the copy of each thread does not affect the copies of other thread objects ).

The following are the key points of threadlocal variables:

Threadlocal variables provides a separate variable for each thread.

Threadlocal instances are usually used as static private static fields in a class, which is used to associate a thread.

When multiple threads access the threadlocal instance, each thread maintains an independent copy of the variable provided by threadlocal.

Common use can be seen in the DAO mode. When the DAO class is used as a singleton class, the connection is maintained independently by each thread, without affecting each other. (Thread-based Singleton)

Threadlocal is hard to understand. The following reference connections help you better understand it.

Good article on threadlocal on IBM developerworks, understanding threadlocal, and managing
Data: good example and refer Java API docs

5. When will an invalidmonitorstateexception be thrown? Why?

If the current thread does not obtain the Lock of this object when calling any method in wait ()/notify ()/notifyall, then the illegalmonitorstateexception will be thrown (that is, when the program still tries to call wait ()/notify ()/notifyall () When no synchronization block or synchronization method of the object is executed ). Because this exception is a subclass of runtimeexcpetion, it does not have to be captured (although you can capture it as long as you want). As a runtimeexception, this exception will not occur in wait (), notify
(), Policyall () method signature is mentioned.

6. What is the difference between sleep (), suspend (), and wait?

Thread. Sleep () puts the current thread in the not runnable state at the specified time. The thread keeps holding the monitor of the object. For example, if a thread is currently in a synchronization block or method, other threads cannot enter the block or method. If another thread calls the interrupt () method, it will wake up the "Sleep" thread.

Note: Sleep () is a static method. This means that it is only valid for the current thread. A common error is the call of T. Sleep () (here t is a thread different from the current thread ). Even if you execute T. Sleep (), the current thread goes to sleep, not the T thread. T. Suspend () is an out-of-date method. Using suspend () causes the thread to enter the stuck state. This thread will keep holding the monitor of the object, and suspend () is prone to deadlock.

Object. Wait () causes the current thread to be out of the "not running" state. Unlike sleep (), wait is the object method rather than the thread. Call object. when wait () is used, the thread first needs to obtain the object lock of this object. The current thread must keep synchronizing the Lock Object and add the current thread to the waiting queue, then another thread can synchronize the same object lock to call the object. Y (), which will wake up the thread in the waiting state and then release the lock. Basically, wait ()/notify () is similar to sleep ()/interrupt (), except that the former needs to obtain the object lock.

7. What happens when I use synchronization in static methods?

When synchronizing static methods, the "class" object of the class is obtained. Therefore, when a thread enters the static method of synchronization, the thread monitor obtains the object lock of the class, other threads cannot enter any static synchronization method of this class. Unlike the instance method, because multiple threads can simultaneously access different instance synchronization instance methods.

8. When a synchronization method has been executed, can the thread call the non-synchronous instance method on the object?

Yes. A non-synchronous method can always be called without any problems. In fact, Java does not perform any check for non-synchronous methods, and the lock object is only checked in the synchronous method or synchronous code block. If a method is not declared as synchronous, it will still be called even if you are using shared data Java, rather than checking whether it is secure, so be careful in this case. Whether a method is declared as synchronous depends on the critial section access. If the method does not access the critical section (shared resource or data structure), it is unnecessary to declare it as synchronous.

The following example shows that the common class has two methods: synchronizedmethod1 () and Method1 (). The mythread class calls these two methods in an independent thread.

 
 
  1. public class Common {
  2. public synchronized void synchronizedMethod1() {
  3. System.out.println ("synchronizedMethod1 called");
  4. try {
  5. Thread.sleep (1000);
  6. } catch (InterruptedException e) {
  7. e.printStackTrace ();
  8. }
  9. System.out.println ("synchronizedMethod1 done");
  10. }
  11. public void method1() {
  12. System.out.println ("Method 1 called");
  13. try {
  14. Thread.sleep (1000);
  15. } catch (InterruptedException e) {
  16. e.printStackTrace ();
  17. }
  18. System.out.println ("Method 1 done");
  19. }
  20. }
 
 
  1. public class MyThread extends Thread {
  2. private int id = 0;
  3. private Common common;
  4. public MyThread (String name, int no, Common object) {
  5. super(name);
  6. common = object;
  7. id = no;
  8. }
  9. public void run () {
  10. System.out.println ("Running Thread" + this.getName ());
  11. try {
  12. if (id == 0) {
  13. common.synchronizedMethod1();
  14. } else {
  15. common.method1();
  16. }
  17. } catch (Exception e) {
  18. e.printStackTrace ();
  19. }
  20. }
  21. public static void main (String[] args) {
  22. Common c = new Common ();
  23. MyThread t1 = new MyThread ("MyThread-1", 0, c);
  24. MyThread t2 = new MyThread ("MyThread-2", 1, c);
  25. t1.start ();
  26. t2.start ();
  27. }
  28. }

Here is the output of the program:

 
 
  1. Running ThreadMyThread-1
  2. synchronizedMethod1 called
  3. Running ThreadMyThread-2
  4. Method 1 called
  5. synchronizedMethod1 done
  6. Method 1 done

The result indicates that Method1 () is called even if the synchronizedmethod1 () method is executed.

9. Can two threads on an object call two different synchronous instance methods?

No, because an object has synchronized the instance method, the thread obtains the object lock of the object. Therefore, other synchronization methods can be executed only after the method is executed to release the object lock. The code example below is very clear: the common class includes the synchronizedmethod1 () and synchronizedmethod2 () methods, and mythread calls these two methods.

 
 
  1. public class Common {
  2. public synchronized void synchronizedMethod1() {
  3. System.out.println ("synchronizedMethod1 called");
  4. try {
  5. Thread.sleep (1000);
  6. } catch (InterruptedException e) {
  7. e.printStackTrace ();
  8. }
  9. System.out.println ("synchronizedMethod1 done");
  10. }
  11. public synchronized void synchronizedMethod2() {
  12. System.out.println ("synchronizedMethod2 called");
  13. try {
  14. Thread.sleep (1000);
  15. } catch (InterruptedException e) {
  16. e.printStackTrace ();
  17. }
  18. System.out.println ("synchronizedMethod2 done");
  19. }
  20. }
 
 
  1. public class MyThread extends Thread {
  2. private int id = 0;
  3. private Common common;
  4. public MyThread (String name, int no, Common object) {
  5. super(name);
  6. common = object;
  7. id = no;
  8. }
  9. public void run () {
  10. System.out.println ("Running Thread" + this.getName ());
  11. try {
  12. if (id == 0) {
  13. common.synchronizedMethod1();
  14. } else {
  15. common.synchronizedMethod2();
  16. }
  17. } catch (Exception e) {
  18. e.printStackTrace ();
  19. }
  20. }
  21. public static void main (String[] args) {
  22. Common c = new Common ();
  23. MyThread t1 = new MyThread ("MyThread-1", 0, c);
  24. MyThread t2 = new MyThread ("MyThread-2", 1, c);
  25. t1.start ();
  26. t2.start ();
  27. }
  28. }

10. What is a deadlock?

A deadlock means that two or more threads are infinitely blocked, and each thread waits for the required resources. This situation may occur when two threads attempt to obtain the Lock of other resources, and each thread falls into an infinite waiting for the release of the lock of other resources, unless a user process is terminated. For Java API, the thread deadlock may occur in the following situations.

  • When two threads call thread. Join ()
  • When two threads use nested synchronization blocks, one thread occupies the required locks of the other thread and is blocked when waiting for each other, a deadlock may occur.

11. What is a thread starved to death, and what is a live lock?

Although thread starvation and live locks do not want to be the same common problems as deadlocks, they are the same for concurrent programming designers.

When all threads are blocked, or the required resources are invalid and cannot be processed, there is no non-blocking thread to make the resources available. The thread lock in Java API may occur in the following situations:

  • When all threads execute object. Wait (0) in the program, the parameter is 0 for the wait method. The program will send a live lock until there is a thread on the corresponding object that calls object. Every y () or object. Every yall ().
  • When all threads are stuck in an infinite loop.

The questions here are not detailed. I believe there are still many important questions that have not been mentioned. What other questions do you think should be included in this question? You are welcome to share any questions and suggestions in the comments.

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.