In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What are the knowledge points of this article "Android Thread, Multithreading and Thread Pool Test questions?" most people do not understand, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Android Thread, Multithreading and Thread Pool Test questions what are there" 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:
Wake up a single thread waiting on this object monitor
NotifyAll ():
Notify all threads waiting for the competing resource
Wait:
Release the lock on 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? (1) 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?
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 an instance of ReentrantLock
Lock () acquires lock unlock () releases lock
4) use local variable ThreadLocal to realize thread synchronization
Each thread keeps 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
5) use atomic variables
For example, 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) use blocking queue to realize thread synchronization
For example, LinkedBlockingQueue
9. How to ensure thread safety?
Thread safety is reflected in three methods:
1) atomicity:
Provide 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. Another type of LOCK is the code-level lock provided by JDK, which relies on CPU instructions, typically ReentrantLock.
2) visibility:
Changes made by one thread to the 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) order:
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
The problem of the number of multithreads, in general, the number of multithreads should be equal to the number of machine CPU cores-1.
1. How to make n threads sequentially traverse the List collection containing n elements import java.util.ArrayList;import java.util.List;import org.apache.commons.lang3.ArrayUtils;public class Test_4 {/ * multithreaded processing list * * @ param data data list * @ param threadNum threads * / public synchronized void handleList (List data, int threadNum) {int length = data.size () Int tl = length% threadNum = 0? Length / threadNum: (length / threadNum + 1); for (int I = 0; I
< threadNum; i++) { int end = (i + 1) * tl; HandleThread thread = new HandleThread("线程[" + (i + 1) + "] ", data, i * tl, end >Length? Length: end); thread.start ();}} class HandleThread extends Thread {private String threadName; private List data; private int start; private int end; public HandleThread (String threadName, List data, int start, int end) {this.threadName = threadName; this.data = data; this.start = start This.end = end;} public void run () {List subList = data.subList (start, end) / * .add ("^ & *") * /; System.out.println (threadName+ "processed" + subList.size () + "!") ;} public static void main (String [] args) {Test_4 test = new Test_4 (); / / prepare data List data = new ArrayList (); for (int I = 0; I < 6666; iTunes +) {data.add ("item" + I);} test.handleList (data, 5) System.out.println (ArrayUtils.toString (data));}} 2. List multithreaded concurrent read read existing list object / / test read List thread class, about 34 seconds package com.thread.list;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class Main {public static void main (String [] args) {List list = new ArrayList () Map map = new HashMap (); for (int I = 0
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.