Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze threads,

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to analyze threads, the content is concise and easy to understand, it can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

1. Three ways to start a thread?

1) inherit the Thread class, override the run () method, and write the task to be completed new Thread (). Start () in the body of the run () method.

2) implement the Runnable interface and the run () method new Thread (new MyRunnable ()). Start ()

3) implement the Callable interface MyCallable class, implement the call () method, use the FutureTask class to wrap the Callable object, use the FutureTask object as the target of the Thread object to create and start the thread; call the get () method of the FutureTask object to get the return value of the child thread after execution.

FutureTask ft = new FutureTask (new MyCallable ()); new Thread (ft). Start ()

2. The difference between run () and start () methods

The run () method is just the thread's body method and, like the normal method, does not create a new thread. Only when the start () method is called will a new thread be started, the new thread will call the run () method, and the thread will start execution.

3. How to control the number of concurrent access threads allowed by a method?

Create the Semaphore variable, Semaphore semaphore = new Semaphore (5, true); when the method enters, request a signal, wait if the signal is used up, the method runs out, release a signal, and the released signal can be used by the new thread.

4. The difference between wait and seelp methods in Java

The wait () method belongs to the Object class. When the method is called, the thread will abandon the object lock. Only after the object calls the notify () method will the thread enter the object lock pool to acquire the object lock and enter the running state.

The sleep () method belongs to the Thread class. Sleep () causes the program to suspend execution for a specified time and give up the CPU, but its monitoring state is still preserved. When the specified time is up, it will return to the running state, and the thread in the sleep () method will not release the object lock.

5. Talk about the understanding of wait/notify keyword

Notify: wakes up a single thread waiting on this object monitor

NotifyAll (): notifies all threads waiting for the competing resource

Wait: releases the lock of obj, causing the current thread to wait, and other threads directly call the notify () or notifyAll () method of this object.

When you call the wait () or notify () / notifyAll () method, be sure to lock the competing resources, usually in the synchronized (obj) code.

When obj.notify/notifyAll is called, the calling thread still holds the obj lock, so although the waiting thread is awakened, it is still unable to acquire the obj lock. It is not until the calling thread exits the synchronized block and releases the obj lock that other waiting threads have a chance to obtain the lock to continue execution.

6. What causes thread blocking?

General thread blocking

1) Thread executes the Thread.sleep (int millsecond) method, abandons CPU, sleeps for a period of time, and resumes execution after a period of time

2) the thread executes a piece of synchronization code, but cannot obtain the relevant synchronization lock, so it can only enter the blocking state and resume execution until the synchronization lock is acquired.

3) Thread executes the wait () method of an object, enters the blocking state directly, and waits for other threads to execute the notify () / notifyAll () operation.

4) the thread performs some IO operations and enters the blocking state because it waits for related resources, such as System.in, but does not receive input from the keyboard.

5) Thread comity, the Thread.yield () method pauses the currently executing thread object and gives the execution opportunity to the same or higher priority thread, but it does not put the thread into the blocking state, the thread is still in the executable state and may be allocated CPU time again at any time.

Thread autopsy, join () method, when the current thread calls another thread's join () method, the current thread enters the blocking state until the end of the other thread, and the current thread changes from blocking to ready state.

6) the thread executes suspend () to put the thread into the blocking state, and the resume () method must be called to make the thread return to the executable state.

7. How does the thread shut down?

1) use flag bit

2) use the stop () method, but this method is like turning off the power of a computer, which may cause unexpected problems

3) use interrupt interrupt ()

Public class Thread {/ / interrupts the current thread public void interrupt (); / / determines whether the current thread is interrupted public boolen isInterrupt (); / / clears the interrupt state of the current thread and returns the previous value public static boolen interrupted ();}

However, calling the interrupt () method simply passes the interrupt request message, and does not mean that the target thread should be stopped immediately.

8. Talk about the method of synchronization in java

The reason for the need for synchronization is that in multithreaded concurrency control, when multiple threads operate a shareable resource at the same time, if no synchronization mechanism is adopted, the data will be inaccurate, so it is necessary to add a synchronization lock. ensure that the thread is called by other threads before the operation is completed, thus ensuring the uniqueness and accuracy of the variable.

1) synchronized decorates synchronization code blocks or methods

Because every object in java has a built-in lock, when you modify a method with this keyword, the built-in lock protects the entire method. Before calling this method, you need to obtain a built-in lock, otherwise you will be in a clogged state.

2) volatile modification variable

To ensure the visibility of variables between threads, each time a thread accesses a volatile-decorated variable, it is read from memory instead of cache, so that each thread accesses the same variable. And use a memory barrier.

3) ReentrantLock reentrant lock, its common method is ReentrantLock (): create a ReentrantLock instance

Lock () acquires lock unlock () releases lock

4) use the local variable ThreadLocal to achieve thread synchronization, and each thread will save a copy of the variable, which is independent of each other, so that each thread can modify its own copy at will without affecting other threads.

The common method ThreadLocal () creates a thread local variable; get () returns the current thread copy variable locally for this thread; initialValue () returns the current thread initial value of this thread local variable; set (T value) sets the value in the current thread copy of this thread variable to value

Using atomic variables such as AtomicInteger, the common method AtomicInteger (int value) creates an AtomicInteger integer with a given initial value; addAndGet (int data) adds the given value to the current value atomically

6) using blocking queues to synchronize LinkedBlockingQueue with threads

9. How to ensure thread safety?

Thread safety is reflected in three methods:

1) atomicity: provides mutually exclusive access, and only one line and data can be operated at a time.

There are many atomic classes available in JDK, such as AtomicInteger\ AtomicBoolean\ AtomicLong, which accomplish atomicity through CAS. There are two kinds of locks provided by JDK: synchronized relies on JVM to implement locks, and only one thread can operate at a time within the scope of the keyword object. The other is LOCK, which is provided by JDK.

Code-level locks, which rely on CPU instructions, are typically ReentrantLock.

2) visibility: changes made by one thread to main memory are seen by other threads in time.

JVM provides the visibility of synchronized and volatile,volatile through memory barrier and prohibiting reordering. Volatile will add a store barrier instruction after the write operation to flush the shared variable values in the local memory to the main memory during the write operation. During the read operation, a load instruction will be added before the read operation to read the shared variables from memory.

3) orderability: instructions are not reordered by the compiler.

Orderliness can be guaranteed by volatile, synchronized and Lock.

10. Can two processes be written or read at the same time? How to prevent the synchronization of processes?

I think it can be achieved, for example, there is no problem for both processes to read calendar process data, but if they write at the same time, there should be conflicts.

You can use shared memory to achieve data sharing between processes.

11. Inter-thread operation List

12. The life cycle of objects in Java

1) creation phase (Created): allocate storage space to objects, start to construct objects, initialize static members from superclass to subclass, initialize superclass member variables sequentially, call superclass constructor recursively, subclass member variables initialize sequentially, and subclass constructor call.

2) In Use: the object is held by at least one strong reference.

3) invisible phase (Invisible): the program runs beyond the scope of the object

4) Unreachable: this object is no longer held by strong references

5) Collection phase (Collected): assuming that the object overrides the finalize () method and has not been executed, the method will be executed.

6) Finalized: the object is still unreachable after running the finalize () method, waiting for the garbage collector to reclaim the object space.

7) object space reallocation phase (De-allocated): the garbage collector reclaims or redistributes the memory space occupied by the object, and the object disappears completely.

13. Multithreaded access and function of static synchronized method

Static synchronized controls access to all instances of the class, no matter how many objects are new, there is only one, so all objects of the class are locked. Restrict all instances of this class in multithreading from accessing the corresponding code of the class in JVM at the same time.

14. The problem of simultaneous access by two synchronized methods and two threads in the same class

If synchronized modifies a static method and locks the class object of the current class, you need to obtain the lock of the current class object before entering the synchronization code

The common method locks the current instance object and obtains the lock of the current instance before entering the synchronization code

Synchronize the code block, lock the object in parentheses, lock the given object, and obtain the given object lock before entering the synchronous code block library

If two threads access the synchronized method of the same object, there will be competition, if it is a different object, it will not affect each other.

15. The principle of volatile

Shared variables decorated with volatile variables will have an extra assembly code when writing. The instruction of the lock addl $0x0 preceded lock prefix will write the data of the current processor cache line back to the system memory under the multi-core processor. This write-back operation will invalidate the data cached in the memory address in other CPU. At the same time, the lock prefix also acts as a memory barrier, limiting the order of memory operations.

16. Synchronized principle

Synchronized implements the locking mechanism through the object header (markword) of the object. Every object in java has an object header, which can provide the basis for synchronized implementation, and can be used as a lock object. At the bytecode level, synchronized blocks are synchronized by inserting monitorenter monitorexit. Hold the monitor object and implement the locking mechanism by entering and exiting the Monitor object.

17. Talk about the understanding of NIO

NIO (New Input/ Output) introduces a channel-and buffer-based method of I _ New Input/ Output, which can use the Native function library to allocate out-of-heap memory directly, and then operate through a DirectByteBuffer object stored in the Java heap as a reference to this memory, avoiding copying data back and forth in the Java heap and the Native heap.

NIO is a synchronous non-blocking IO model. Synchronization means that the thread constantly polls whether the IO event is ready, and non-blocking means that the thread can do other tasks while waiting for IO.

The core of synchronization is that Selector,Selector takes the place of the thread itself to poll IO events, avoiding blocking and reducing unnecessary thread consumption; the core of non-blocking is the channel and buffer, when the IO event is ready, you can ensure the success of IO by writing buffer, without thread blocking waiting.

The difference between synchronized and volatile keywords

The difference between synchronized and Lock

Comparison of ReentrantLock, synchronized and volatile

1) volatile: solves the visibility of variables among multiple threads, but does not guarantee atomicity, and can only be used to modify variables without blocking. Volatile shields compilation instruction rearrangements, does not put the instructions behind it in front of the memory barrier, and does not put the previous instructions behind the memory barrier. A singleton mode that is mostly used for parallel computing. Volatile stipulates that CPU must read data from memory every time, not from CPU cache, which ensures that multi-threads always get the latest values in multi-CPU computing.

2) synchronized: mutex lock, operation mutex, concurrent thread, serial acquisition of lock, serial execution of code. What is solved is the synchronization of access to shared resources between multiple threads, which ensures atomicity as well as visibility indirectly, because it synchronizes data in private and public memory. Can be used to modify methods and code blocks. There will be a blockage. When an exception occurs in synchronized, the lock held by the thread is automatically released, so it does not cause a deadlock. Unfair lock, competing for resources every time.

3) lock is an interface, synchronized is the keyword in java, and synchronized is the implementation of the built-in language. Lock allows the thread waiting for the lock to respond to the interrupt. When an exception occurs, if the lock is not released actively through unLock (), it may cause a deadlock, so you need to release the lock in the finally block when using Lock.

4) ReentrantLock can reenter the lock, and the lock allocation mechanism is based on thread allocation rather than method call allocation. ReentrantLock has a tryLock method that returns false if the lock is held by another thread to avoid forming a deadlock. Locking the code with smaller particles will save resources and improve the performance of the code. ReentrantLock can realize fair locking and unfair locking. Fair locking means obtaining resources on a first-come-first-served basis. ReentrantReadWriteLock is used in situations where there is more reading and less writing, and there is no need for mutually exclusive scenarios.

Internal implementation of ReentrantLock

Lock principle

Four necessary conditions for deadlock?

How to avoid deadlocks?

Do object locks and class locks affect each other?

What is a thread pool and how to use it?

Concurrency, multithreading and threading model of Java

Talking about the understanding of multithreading

What are the problems that multithreading should pay attention to?

Talk about your understanding of concurrent programming and give examples

Tell me about your understanding of multithreaded synchronization mechanism?

How to ensure the security of multi-thread reading and writing files?

The principle of multithreading breakpoint continuation

The realization of breakpoint continuation

5) knowledge points about concurrent programming (this is rarely used in Android development, so it is recommended to take a look at it more):

Usually Android development can do less concurrent programming, Thread this class is often used, but if we want to improve ourselves, we must not stay on the surface, we should also learn about java about thread-related source level things.

The above is how to analyze threads, have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report