Summary of multithreaded questions in Java programmer interview

  • 2020-05-12 02:45:31
  • OfStack

Many of the core Java interview questions come from multi-threading (Multi-Threading) and the set framework (Collections Framework), and good practical experience is required to understand the core threading concept. This article has collected some typical questions about Java threads that are often asked by senior engineers.

What is multithreading in Java?

In multithreaded programs, synchronization can control access to Shared resources. If there is no synchronization, when one Java thread is modifying one Shared variable, another thread is using or updating the same variable, which can easily result in an error in the program.

1. Explain several methods to realize multithreading ?

1 Java thread can implement Runnable interface or inherit Thread class. When you plan multiple inheritance, Runnable is preferred.

2. What is the difference between Thread.start () and Thread.run ()?

The Thread.start () method (native) starts the thread to a ready state, and when cpu allocates time to the thread, the run () method is scheduled to execute by JVM.

3. Why do we need the run () and start () methods when we can just use the run () method to do the job?

We need run () & start () these two methods is because JVM create a separate thread is different from the ordinary method calls, so the work are done by thread start method, start by local method implementation, need to display is called, using these two methods is a further advantage is any one object can be used as a thread running, as long as implements Runnable interface, it is avoid caused by inherited Thread class Java problem of multiple inheritance.

4. What is ThreadLocal class and how to use it?

ThreadLocal is a local variable at the level of one thread, not a "local thread". ThreadLocal provides a separate copy of the variable for each thread that USES the variable, and each thread modifies the copy without affecting the copy of the other thread object.

Here are the key points for thread local variables (ThreadLocal variables) :

A thread-local variable (ThreadLocal variables) conveniently provides a separate variable for each thread.

An ThreadLocal instance usually appears as a static private (private static) field in a class that is used to associate a thread.

When multiple threads access an ThreadLocal instance, each thread maintains a separate copy of the variable provided by ThreadLocal.

Common usage can be seen in the DAO pattern. When the DAO class is treated as a singleton class, the database link (connection) is maintained independently by each thread. (thread-based singleton)

5. When to throw an InvalidMonitorStateException exception and why?

When any of the methods in wait ()/notify ()/notifyAll () are called, an IllegalMonitorStateException exception is thrown if the current thread does not acquire the lock on the object (that is, when the program attempts to call wait ()/notify ()/notifyAll () without executing any of the synchronized blocks or synchronized methods on the object). Since this exception is a subclass of RuntimeExcpetion, it is not bound to be caught (although you can catch as much as you like). As RuntimeException, this type of exception is not referred to in wait (),notify (),notifyAll () method signatures.

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

Thread.sleep () causes the current thread to be "not running" (Not Runnable) at the specified time. Thread 1 holds the monitor of the object directly. For example, if a thread is currently in a synchronized block or method, other threads cannot enter the block or method. If another thread calls the interrupt () method, it will wake up the "sleeping" thread.

Note: sleep () is a static method. This means that it is only valid for the current thread, and a common error is to call t.sleep (), where t is a different thread from the current thread. Even when t.sleep () is executed, the current thread goes to sleep, not the t thread. t.suspend () is an outmoded method that USES suspend () to cause a thread to go into a stagnant state. The thread will hold the monitor of the object directly, and suspend () is prone to deadlock problems.

object.wait () makes the current thread in an "unrunnable" state, unlike sleep () where wait is the object method instead of thread. When calling object.wait (), the thread must first acquire the object lock of this object, the current thread must keep synchronization with the lock object and add the current thread to the waiting queue, then another thread can synchronize with the other object lock to call object.notify (), which will wake up the waiting thread and then release the lock. Basically, wait ()/notify () is similar to sleep ()/interrupt (), except that the former requires the acquisition of an object lock.

7. What happens when synchronization is used on static methods?

When a static method is synchronized, the "Class" object of the class is acquired, so when a thread enters a synchronized static method, the thread monitor acquires the object lock of the class itself, and no other thread can enter any static synchronized method of the class. It is not like instance methods, because multiple threads can access different instances at the same time to synchronize instance methods.

8. Can a thread call an asynchronous instance method on an object when a synchronized method has been executed?

Yes, an asynchronous method can always be called without any problems. In fact, Java does no checking for asynchronous methods, and the lock object is only checked in synchronized methods or synchronized code blocks. If a method is not declared as synchronized, Java will be called even if you are using Shared data without checking for security, so be careful in this case. Whether a method is declared synchronous or not depends on the critical section access (critial section access), and if the method does not access the critical section (Shared resource or data structure), it is not necessary to declare it synchronous.

Here's an example: the Common class has two methods, synchronizedMethod1() and method1(), which are called in separate threads by the MyThread class.


public class Common { 
    public synchronized void synchronizedMethod1() { 
      System.out.println("synchronizedMethod1 called"); 
      try { 
        Thread.sleep(1000); 
      } catch (InterruptedException e) { 
        e.printStackTrace(); 
      } 
      System.out.println("synchronizedMethod1 done"); 
    } 
 
    public void method1() { 
      System.out.println("Method 1 called"); 
      try { 
        Thread.sleep(1000); 
      } catch (InterruptedException e) { 
        e.printStackTrace(); 
      } 
      System.out.println("Method 1 done"); 
    } 
  } 

public class MyThread extends Thread { 
    private int id = 0; 
    private Common common; 
 
    public MyThread(String name, int no, Common object) { 
      super(name); 
      common = object; 
      id = no; 
    } 
 
    public void run() { 
      System.out.println("Running Thread" + this.getName()); 
      try { 
        if (id == 0) { 
          common.synchronizedMethod1(); 
        } else { 
          common.method1(); 
        } 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
 
    public static void main(String[] args) { 
      Common c = new Common(); 
      MyThread t1 = new MyThread("MyThread-1", 0, c); 
      MyThread t2 = new MyThread("MyThread-2", 1, c); 
      t1.start(); 
      t2.start(); 
    } 
  } 

Here is the output of the program:

Running ThreadMyThread-1
synchronizedMethod1 called
Running ThreadMyThread-2
Method 1 called
synchronizedMethod1 done
Method 1 done

It turns out that even if the synchronizedMethod1() method is executed, method1() will be called.

9. Can two threads call two different synchronized instance methods on one object?

No, because an object has synchronized its instance methods, the thread acquires the object's object lock. So only after this method releases the object lock can the other synchronization methods be executed. The following code example is clear: the Common class has the synchronizedMethod1() and synchronizedMethod2() methods that MyThread calls.


public class Common { 
    public synchronized void synchronizedMethod1() { 
      System.out.println("synchronizedMethod1 called"); 
      try { 
        Thread.sleep(1000); 
      } catch (InterruptedException e) { 
        e.printStackTrace(); 
      } 
      System.out.println("synchronizedMethod1 done"); 
    } 
 
    public synchronized void synchronizedMethod2() { 
      System.out.println("synchronizedMethod2 called"); 
      try { 
        Thread.sleep(1000); 
      } catch (InterruptedException e) { 
        e.printStackTrace(); 
      } 
      System.out.println("synchronizedMethod2 done"); 
    } 
  } 

public class MyThread extends Thread { 
 private int id = 0; 
 private Common common; 
 
 public MyThread(String name, int no, Common object) { 
  super(name); 
  common = object; 
  id = no; 
 } 
 
 public void run() { 
  System.out.println("Running Thread" + this.getName()); 
  try { 
  if (id == 0) { 
   common.synchronizedMethod1(); 
  } else { 
   common.synchronizedMethod2(); 
  } 
  } catch (Exception e) { 
  e.printStackTrace(); 
  } 
 } 
 
 public static void main(String[] args) { 
  Common c = new Common(); 
  MyThread t1 = new MyThread("MyThread-1", 0, c); 
  MyThread t2 = new MyThread("MyThread-2", 1, c); 
  t1.start(); 
  t2.start(); 
 } 
 } 

What is a deadlock

A deadlock is when two or more threads are blocked indefinitely, waiting on each other for the required resources. This can happen when two threads try to acquire a lock on another resource, and each thread gets stuck waiting indefinitely for the other resource lock to be released, unless a user process is terminated. In the case of JavaAPI, thread deadlocks can occur under 1.

When two threads call each other Thread.join () When two threads use a nested synchronized block, one thread holds the necessary locks for the other, and a deadlock can occur when they are blocked while waiting for each other.

11, what is thread starvation, what is a live lock?

Thread starvation and live locking, while not necessarily a common problem with deadlocks, are like one-encounter one-for designers of concurrent programming.

When all threads are blocked or cannot be processed because the required resource is invalid, no non-blocking thread exists to make the resource available. Thread live locks in JavaAPI can occur in the following situations:

When all threads execute Object.wait (0) in the program, the wait method takes the parameter 0. The program issues a live lock until a thread on the corresponding object calls Object.notify () or Object.notifyAll (). When all threads are stuck in an infinite loop.

Related articles: