Some problems with java multithreading

1. What is a thread?

A thread is the smallest unit of operation scheduling in the operating system.

included in the process;

Using multithreading can speed up the processing of intensive tasks. The Java language provides good support for multithreading.

 

2. What is the difference between a thread and a process?

A process can have many threads, and each thread performs a different task.

Different processes have different memory spaces, and all threads share a memory space.

Each thread has separate stack memory to store local data.

 

3. How is the thread implemented?

Inherit the Thread class and call the Runnable interface;

The single root of Java inheritance, implements the Runnable interface, and rewrites the run() method to implement threads.

 

4. What is the difference between Start and Run?

Start starts the newly created thread, and start internally calls the run method;

If the run method is called directly, it will only be called in the original thread. If no new thread is started, the start method will start a new thread.

 

5. What is the difference between Runable and Callable?

Runnable has been available since jdk1.0, and Callable was added in jdk1.5;

Callable's call() method can have return values ​​and throw exceptions, Runnable's run() method does not have these functions;

Callable can also return a Future object loaded with the result of the calculation.

 

6. Java's memory model?

Java's memory model specifies and guides Java programs to have deterministic behavior between different memory architectures, CPUs and operating systems;

They are especially important in the case of multithreading, and the memory model provides guarantees for visibility between multiple threads;

                 

There is a shared memory space in the memory model - the main memory, which holds the shared variables of all threads, and the local memory of each thread holds only a copy of the shared variables;

When thread A changes, the copy information is flushed to the main memory; thread B reads the information changed by thread A in the main memory.

 

7. What is a volatile variable?

  In the absence of synchronization in concurrent programming, multi-thread operations on member variables are transparent and visible to other threads;

vlatile can guarantee that the next read operation will happen after the previous write operation, only member variables can use it.

 

8. What is thread safety? Is Vector a thread safe class?

In the case of multi-threading, a piece of code is executed at the same time, and the running result is consistent with that of a single thread, which is thread safety;

Vector is thread-safe using synchronized methods; ArrayList is not thread-safe;

 

9. Race condition in Java? example

Multi-threaded competition for some resources, the first program to be executed fails to compete and re-queues, resulting in the entire process not being processed in the expected order, and some uncertain and hard-to-find bugs appear. This situation is a race condition;

For example: out-of-order processing

 

10. How to stop a thread in Java?

There is no API to stop the thread;

JDK1.0 provides, stop(), suspend(), resume() and other methods for controlling threads, which have been deprecated and too violent;

When the run() or call() method is executed, the thread will automatically end;

To end manually, interrupt() can be called to interrupt the thread, with an interrupt flag.

 

11. What happens when an exception occurs in a thread?

If the thread is not caught, it will stop execution and throw an exception UncaughtExceptionHandler;

Thread.getUncaughtExceptionHandler() is provided internally by the JVM to query whether the thread has set exception handling.

 

12. How to share data between two threads?

This can be achieved by sharing objects;

 

13. What is the difference between Notify and NotifyAll?

Notify() wakes up a single thread;

notifAll() wakes up all threads and lets them fight for the lock.

 

14. Why wait, notify, notifyall are not in the thread class?

These methods prevent the Object class;

Because the lock provided by java is an object-level lock, not a thread-level lock, each object has a lock, which is obtained by a thread;

Defined in Thread, it does not conform to the design of object locks.

 

15. What is a ThreadLocal variable?

local thread variable;

Let each thread have ThredLocal, and the race condition is eliminated;

For threads that frequently create objects, using it can reduce the number of objects created, and hold a copy of the variable in the thread-local memory instead of creating it every time;

For example: Use ThreadLocal to make SimpleDateFormat thread-safe;

 

16. What is the difference between Interrupted and isInterrupted methods?

The former will clear the interrupt status, the latter will not;

The interrupt mechanism in Java multi-threading is implemented with internal flags. Calling interrupt to interrupt a thread will set an interrupt flag true. When querying the interrupt status, the flag will be cleared;

The latter is used to query the interrupt status without changing the interrupt status flag;

The former is static and the latter is non-static;

 

17. Why are wait and notify methods called in synchronized code blocks?

Mandatory, otherwise IllegalMonitorStateException will be thrown;

Avoid race conditions between the two;

 

18. Difference between synchronized collections and concurrent collections in Java?

Both synchronized collections and concurrent collections provide suitable thread-safe collections for threads, and concurrent collections have higher scalability;

Before Java 5, there were only synchronous collections, and when multiple threads were concurrent, it would lead to contention, hindering the scalability of the program;

After Java5, concurrent collections, such as ConcurrentHashMap, not only provide thread safety, but also use lock separation and internal partitioning, etc., and have better scalability.

 

19. What is the difference between heap and stack in Java?

The stack is a memory area closely related to threads. Each thread has its own stack memory for storing local variables, method parameters and stack calls. Variables stored in a stack are invisible to other threads;

The heap is a common memory area shared by all threads, and objects are created in the heap;

In order to improve efficiency, the thread will get a cache from the heap to its own stack;

In the case of multi-threading, there is a thread-unsafe problem in reading variables from common memory, and using volatile variables can ensure thread-safety.

 

20. What is a thread pool? Why use it?

Create a certain number of threads to wait for response processing, which is called a thread pool, and the threads in the thread pool are called worker threads;

The Java API provides an Execution framework to create different thread pools;

Why?

It takes expensive resources and time to create a thread. If the task is created, the response time will be longer, which will affect the efficiency;

A single-threaded pool can be created to process one task at a time;

A fixed number of thread pools can be created, or a scalable thread pool to handle multitasking;

Metaphor: a bus stop

 

21. How to solve the producer consumer problem?

A thread produces a task and provides it to other threads for consumption, which belongs to the producer-consumer model;

The producer-consumer problem can be solved through communication between threads. The java API provides wait and notify methods to solve this problem;

A better approach is Semaphore or BlockingQueue to implement a producer-consumer model.

 

22. How to avoid deadlock?

Deadlock is a phenomenon in which two or more processes compete for resources and cause each other to wait and the program is stuck when executing;

Deadlock occurs under the following four conditions:

Mutual exclusion condition, a resource can only be called by one process at a time;

Request and hold conditions, when a process acquires resources and blocks, it keeps the acquired resources;

No deprivation condition, the process has obtained the resource, and it will not be forcibly deprived before the use is completed;

Circular waiting condition, the processes are connected head to tail and wait for the release of resources;

 

To avoid deadlock is to prevent the cyclic waiting condition, set flags and sort all resources in the system, and stipulate that all processes execute in order (ascending or descending) when applying for resources;

 

23. Difference between livelock and deadlock in Java?

Livelock is the phenomenon that the state of the process can be changed, but cannot be executed; for example, when two people meet in the corridor, one lets the other, but cannot be let out.

A deadlock is a process where the state of the process cannot be changed and cannot be executed; for example, when two people meet in a hallway and remain stuck there.

 

24. How to check if a thread owns the lock?

There is a method holdsLock() in Java.lang.Thread, which returns true, the current thread holds the lock;

 

25. What is the difference between synchronized and RentrantLock in Java?

They are all locks;

Use the synchronized keyword as a lock to achieve mutual exclusion. It can lock methods, lock statement blocks, and lock objects, but it cannot extend methods or boundaries other than locks, and it cannot be cancelled in the middle of trying to acquire a lock, etc.;

The lock interface after Java 5 provides more complex control to solve concurrency problems;

The RentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized but with better scalability.

 

26. There are 3 threads, how to ensure that they are executed in order?

There are many ways;

One thread can be started in another thread using the join() method,

For example: A, B, C three threads; join A to b, b to c, start C thread first, and execute in the order of cba;

 

27. What does the yield method in the Thread class do?

You can suspend the currently executing thread object and let the one with higher priority execute first;

It is a static method that ensures that the current thread gives up CPU usage, and does not guarantee that the high priority will be executed. It is possible that the thread will resume immediately after it is suspended;

 

28. What is the concurrency of ConcurrentHashMap in Java?

 ConcurrentHashMap divides the actual map into several parts to achieve its scalability and thread safety;

This division is obtained using concurrency, which is a constructor parameter of the ConcurrentHashMap class constructor, with a default value of 16 to avoid contention in multi-threaded situations.

 

29. What happens if the thread pool is full when you submit a task?

An exception RejectedExecutionException will be thrown; because the thread task cannot be scheduled without extending the thread pool.

 

30. What is the difference between submit and execute methods in thread pool in Java?

Both methods can submit tasks to the thread pool;

The return value type of the execute method is void, which is defined in the Executor interface;

The Submit method returns the future object that holds the calculation result, which is defined in the ExecutorService interface, which extends the Exector interface;

Other thread pool classes ThreadPoolExecutor and ScheduledThreadPoolExecutor have these methods;

 

31. What is a blocking method?

It means that the program will wait for the method to complete, and will not do other things during the period;

The accept method of the ServerSocket class is a blocking method that will always wait for the client to connect;

Blocking means that the current thread will be suspended before the result of the call is returned, and it will not return until the result is obtained;

 

32. What is ReadWriteLock in Java?

Read-write locks are used to improve the performance of concurrent programs;

A new interface in Java5, a read-write lock maintains a pair of associated locks, one for read operations and one for write operations;

Read locks are shared and write locks are exclusive.

 

33. What is a busy loop in multithreading?

The busy loop is that the developer uses an empty loop to make a thread wait, and always holds the control of the CPU;

Unlike wait(), sleep(), yield() and other methods, which give up control of the CPU;

The benefit is to preserve the CPU cache, reduce thread waits, and avoid rebuilding the cache.

 

34. What happens if a thread inside a synchronized block throws an exception?

The thread will release the lock;

 

35. What is the double-checked lock in the singleton pattern?

It's the old way to create thread-safe, singleton patterns;

When the singleton instance is first created it tries to use a single lock for performance optimization, but it is so complicated that it is hardly used.

 

36. How to create thread safe singleton in java?

Double retrieval implements singleton;

Singletons can also be created through the JVM's class loading and static variable initialization features;

Or use enumeration to achieve;

The above three are all thread-safe available;

 

37. Write 3 best practices for multithreading that you follow?

1) Give the thread a meaningful name

It is convenient to find bugs or track thread execution;

2) Avoid locking and narrowing the sync range

Locks are expensive, and context switching consumes more time and space. Minimizing the use of synchronization locks and narrowing critical sections is conducive to improving performance.

3) Use more synchronization classes and less wait and notify

Synchronization classes like CountDownLatch, Semaphore, CyclicBarrier and Exchanger simplify coding;

It is difficult for wait and notify to achieve relatively complex control flow control;

Use advanced synchronization tools to help optimize threads;

4) Use more concurrent collections and less synchronous collections

Concurrent collections scale better than synchronous collections

 

38. How to force start a thread?

The thread is controlled by the thread scheduler, and there is no API for responding in java.

 

39. What is the difference between the methods of calling wait and sleep in Java multithreading?

can put the thread into a waiting state;

The wait method is used for inter-thread communication, it releases the lock if the wait condition is true and other threads are woken up;

The sleep method only releases the resources of the CPU, stops the execution of the current thread, and does not release the lock;

 

 

 

  • other

1. What is the difference between CyclicBarrier and CountDownLatch?

Both CyclicBarrier and CountDownLatch can make a group of threads wait for other threads;

The difference is that CountdownLatch cannot be reused.

 

2. What is FutureTask?

In java concurrent programming, FutrueTask represents an asynchronous operation that can be cancelled;

It has methods such as start operation, cancel operation, query operation, and retrieval operation. The result can be retrieved only after a single operation is completed, and get will be blocked if the operation is not completed.

Asynchronous operations also call the Runnable interface, which can be handed over to Executor for execution.

 

3. Why should wait conditions be checked in a loop?

Threads in the waiting state may receive false alarms and false wake-ups. If the waiting is not checked in the loop, the program will exit if the conditions are not met;

When a thread is notified, it is not considered that its original state is still valid, because it may change during this time.

 

4. How to get thread stack in java?

The JVM will save the state of all threads to a log file or output it to the console;

Ctrl+Break key combination in Windows to get;

Use the kill -3 command to obtain it under Linux;

The industry can use the jps tool to find the id;

 

5. Which parameter in the JVM is used to control the stack size of the thread?

-Xss is used to control the thread stack size;

 

6. What is a semaphore in Java?

is a new synchronization class, which is a counting signal;

The semaphore maintains a permission set. Unauthorized thread requests will be blocked, and only permission requests can enter the queuing state;

Semaphore only counts signals for which licenses are available;

Semaphores are commonly used in multi-threaded code, such as database connection pools, etc.

 

7. Is Swing thread safe? Why?

not thread safe;

Because the components provided by swing cannot be modified in multiple threads, all updates to GUI components need to be completed in the AWT thread;

Swin provides two callback methods, synchronous and asynchronous, to update;

 

8. What is the difference between invokeAndWait and invokeLater methods in Java?

The role is to update GUI components from the current thread;

The former updates GUI components synchronously, such as a progress bar. Once updated, the progress bar will change accordingly;

The latter requests the dispatching thread to update the component, such as a progress bar. Once updated, it is not updated. It needs to wait for the dispatching thread to complete the update before it is finally updated.

 

9. Which methods in the Swing API are thread safe?

Swing is not thread safe, some of its methods are thread safe;

For example: repaint(), revalidata(), setText() method of JTextComponent and insert() method and append() method of JTextArea, etc.

 

10. What is the difference between volatile variable and atomic variable in Java?

The volatile variable in Java can ensure the look-ahead relationship, and the write operation will occur before the subsequent read operation, but it does not guarantee atomicity;

For example, if the count variable is modified with volatile, then the count++ operation is not atomic;

The atomic method provided by the AtomicInteger class can make this operation atomic;

 

11. What is the fork join framework in Java?

Fork join framework is a tool that appeared in JDK7, java developers can use it to make full use of the multiplexer on modern servers;

All available processing power can be called up to improve program performance;

It uses a work stealing algorithm, worker threads that can complete more tasks, can steal tasks from other threads to execute.

Guess you like

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