A summary of multithreading problems in a Java Programmer's interview _java

Source: Internet
Author: User
Tags inheritance instance method thread class

Many of the core Java face questions come from multithreaded (multi-threading) and collection frameworks (collections framework), which are required to understand the core threading concepts. This article collects some typical Java threading problems that are often asked by senior engineers.

0. What is multithreaded synchronization in Java?

Synchronization can control access to shared resources under multithreaded routines. If there is no synchronization, when a Java thread modifies a shared variable, another thread is using or updating the same variable, which can easily cause the program to have the wrong result.

1, explain the implementation of several methods of multithreading?

A Java thread can implement the Runnable interface or inherit the thread class, and when you intend multiple inheritance, prioritize the implementation of Runnable.

2, Thread.Start () and Thread.run () What is the difference?

The Thread.Start () method (native) starts the thread so that it is ready, and the JVM dispatches the Run () method when the CPU allocates time to the thread.

3. Why do I need the run () and start () method, can we just use the run () method to complete the task?

We need run () &start () because the JVM creates a separate thread that is different from the normal method call, so this work is done by the thread's Start method, which is implemented by the local method and needs to be called in the display. Another benefit of using these two methods is that any object can run as a thread, as long as the Runnable interface is implemented, which avoids the Java multiple inheritance problem caused by inheriting the thread class.

4, what is the ThreadLocal class, how to use it?

ThreadLocal is a thread-level local variable, 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 a copy of the other thread object (translator).

The following are key points for thread-local variables (ThreadLocal variables):

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

ThreadLocal instances typically appear in a class as static private (private static) fields that are used to associate a thread.

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

Common use can be seen in DAO mode, when the DAO class is a single instance class, the database link (connection) is maintained independently by each thread and does not affect each other. (Thread-based single example)

5, when throws Invalidmonitorstateexception exception, why?

When you call any of the methods in Wait ()/notify ()/notifyall (), if the current thread does not get a lock on the object, the Illegalmonitorstateexception exception is thrown ( This means that the program still tries to invoke wait ()/notify ()/notifyall () when no synchronized block or synchronization method is executed for the object. Because the exception is a runtimeexcpetion subclass, the exception is not necessarily captured (although you can capture as long as you wish). As a runtimeexception, such exceptions are not in wait (), notify (), Notifyall () The method signature is mentioned.

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

Thread.Sleep () causes the current thread to be in a "non-run" (not Runnable) state at a specified time. The thread always holds the object's monitor. For example, a thread is currently in a synchronized block or synchronization method, and other threads cannot enter the block or method. If another thread calls the interrupt () method, it wakes up the "sleeping" thread.

Note: Sleep () is a static method. This means that only the current thread is valid, and a common mistake is to invoke T.sleep () (where T is a thread different from the current thread). Even the execution of T.sleep () is also the current thread entering sleep rather than the t thread. T.suspend () is an obsolete method that uses suspend () to cause a thread to stagnate, which holds the object's monitor all the time, and suspend () can easily cause deadlock problems.

Object.wait () causes the current thread to be in a "non-run" state, unlike sleep (), which is a method of object rather than thread. When Object.wait () is invoked, the thread first gets the object lock of the object, the current thread must be synchronized with the lock object, the current thread is added to the wait queue, and then another thread can synchronize the same object lock to invoke Object.notify (), which wakes up the original waiting threads. Then release the lock. Basically wait ()/notify () is similar to sleep ()/interrupt (), except that the former needs to acquire an object lock.

7. What happens when you use synchronization on a static method?

When a static method is synchronized, the class object is obtained, so when one thread enters a synchronized static method, the thread monitor gets the object lock of the class itself, and no other thread can enter any of the static synchronization methods of the class. It is not like an instance method, because multiple threads can access different instance synchronization instance methods at the same time.

8. When a synchronization method has been executed, can the thread invoke the asynchronous instance method on the object?

OK, an asynchronous method can always be invoked without any problems. In fact, Java does not do any checking for asynchronous methods, and lock objects are checked only in the synchronization method or in the synchronized code block. If a method is not declared synchronous, even if you are using the shared data Java will be called, and will not do the check is safe, so in this case to be particularly cautious. Whether a method is declared to be synchronous depends on critical section access (critial), if the method does not access the critical section (shared resource or data structure), it is not necessary to declare it synchronized.

The following example shows that the Common class has two methods SynchronizedMethod1 () and Method1 (), and the Mythread class calls both methods in a separate thread.

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

The results indicate that even if the SYNCHRONIZEDMETHOD1 () method is executed, method1 () is also invoked.

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

No, because an object has synchronized the instance method, the thread gets the object lock of the object. Therefore, you cannot perform other synchronization methods until this method frees the object lock. The following code example is very clear: the Common class has synchronizedMethod1 () and SynchronizedMethod2 () methods, Mythread calls both methods.

 public class Common {public synchronized void SynchronizedMethod1 () {Syste 
      M.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 (); 
 } 
  

10. What is a deadlock

A deadlock is two or more threads that are blocked indefinitely, and the threads wait for resources to each other. This can happen when two threads attempt to acquire a lock on another resource, and each thread is thrown into an infinite wait for another resource lock to be released unless a user process is terminated. As far as JAVAAPI is concerned, thread deadlocks can occur in a situation.

    • When two threads call each other Thread.Join ()
    • When two threads use a nested synchronization block, one thread occupies a required lock on another thread, and a deadlock can occur when the other is blocked while waiting.

11, what is the thread of starvation, what is the living lock?

Threads starved to death and live locks, although not a deadlock-like common problem, are like an encounter for concurrent programming designers.

When all threads are blocked or cannot be processed because the resource required is not valid, non-blocking threads do not exist to make the resource available. Javaapi Centerline Cheng locks can occur in the following situations:

    • When all threads execute object.wait (0) in a program, the wait method with a parameter of 0. The program will have a live lock until the thread calls Object.notify () or Object.notifyall () on the corresponding object.
    • When all the lines are Cheng Ka in an infinite loop.

The problem here is not exhaustive, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.