Multithreading and Concurrency Library of Java Interview Questions

1. Multi-threaded implementation

    (1) Use class Thread

    Write running code in the run method overridden by the Thread subclass

         new Thread() {
    @Override
    public void run() {
    while(true) {
    try {
    Thread.sleep(2000);
   
    catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }.start();

    (2) Implement the Runnable interface

   Write the code in the run method of the Runnable object passed to the Thread object

2 Thread local variable ThreadLocal

    (1) The role and purpose of ThreadLocal:

        ThreadLocal is used to achieve data sharing within threads, that is, for the same program code, multiple modules share a piece of data when running in the same thread, and share another piece of data when running in another thread.

        (2) Each thread calls the set method of the ThreadLocal object. In the set method, first obtain the ThreadLocalMap object of the current thread according to the current thread, and then insert a record into the map. The key is actually the ThreadLocal object, and the value is the respective set method. The value passed in. That is, each thread actually has its own ThreadLocalMap object, the key of the object is the ThreadLocal object, and the value is the specific value set by the user. The ThreadLocal.remove() method can be called at the end of the thread, which will release the memory faster, or not, because the related ThreadLocal variables can also be automatically released after the thread ends.

        (3) Application scenarios of ThreadLocal:
➢ Order processing includes a series of operations: reducing inventory, adding a running ledger, and modifying the general ledger. These operations must be
completed in the same transaction, usually in the same thread. , if the operation of accumulating company receivables fails, the previous
operation should be rolled back, otherwise, all operations should be submitted, which requires these operations to use the same database connection object, and the codes of these operations
are located in different module classes .
➢ Bank transfer consists of a series of operations: Decrease the balance of the transfer account and increase the balance of the transfer account. These two operations should be
completed in the same transaction, they must use the same database connection object, transfer in and transfer out The code for the operations are methods of two different
account objects.
➢ For example, in the ActionContext of Strut2, when the same piece of code is called by different threads to run, the data manipulated by the code is the state and data of
each thread. For different threads, the objects obtained by the getContext method are different. For the same
thread, no matter how many times the getContext method is called and in which module the getContext method is called, the result is the same

indivual.

        (4) How to use ThreadLocal

            ①Create private static ThreadLoacal in the associated data class

            public class SerialNum {// The next serial number to be assigned
        private static int nextSerialNum = 0;
        private static ThreadLocal serialNum = new ThreadLocal() {
    protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};
public static int get() {
return ((Integer) (serialNum.get())).intValue();
}
}

           ②Create ThreadLocal in the Util class

public class HibernateUtil {
private static Log log = LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory; //Define SessionFactory
static {
try {
//Create SessionFactory through default configuration file hibernate.cfg.xml 
sessionFactory = new Configuration( ).configure().buildSessionFactory()
} catch (Throwable ex) {
log.error("Failed to initialize SessionFactory!", ex);
throw new ExceptionInInitializerError(ex);
}
}


//Create a thread local variable session to save Hibernate's Session
public static final ThreadLocal session = new ThreadLocal();
/**
* Get the Session in the current thread
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// If the Session has not been opened, open a new Session
if (s == null) {
s = sessionFactory.openSession(); session.set(s); //Save the newly opened Session to the thread local variable
}
return s;
}


public static void closeSession() throws HibernateException {
//Get the thread local variable and cast it to Session type
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}

}

        ③Create ThreadLocal in Runnable

Create a ThreadLocal inside the thread class. The basic steps are as follows:

        a. In a multi-threaded class (such as ThreadDemo class), create a ThreadLocal object threadXxx to save the object xxx that needs to be isolated between threads.

        b. In the ThreadDemo class, create a method getXxx() to obtain the data to be isolated and accessed. In the method, judge that if the ThreadLocal object is null, an object of the isolated access type should be new () and cast to be applied type

        c. In the run() method of the ThreadDemo class, the data to be operated is obtained by calling the getXxx() method, which ensures that each thread corresponds to a data object, and this object is operated at any time.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325477624&siteId=291194637