When you go to Android for an interview, you usually ask a few Java questions, so you might find the answer to a question very painful, and introduce a thread today.
First look at a few concepts:
Thread: The execution unit in the process that is responsible for program execution. There is at least one thread in a process.
Multithreading: Solve the requirement of multitasking and use CPU resources reasonably. Multi-threaded operation is done according to the CPU switchover, how to switch is determined by the CPU, so multi-threaded operation is uncertain.
Threads in thread Java
Use the Java.lang.Thread class or the Java.lang.Runnable interface to write code to define, instantiate, and start new threads.
A thread class instance is just an object that, like any other object in Java, has variables and methods that live and die on the heap.
In Java, each thread has a call stack, and the thread runs in the background even if no new threads are created in the program.
A Java application always runs from the main () method, and the Mian () method runs inside a thread, which is called the main thread.
Once a new thread is created, a new call stack is generated.
Threads are divided into two categories: the user thread and the waiting thread.
The JVM shuts down automatically when all user threads have finished executing. But the waiting thread is not independent of the JVM, and the waiting thread is typically created by the operating system or the user himself.
There are two ways to create a thread:
First, inherit the thread class and extend the threads.
class MyThread extends Thread { @Override publicvoidrun() { super.run(); // Perform time-consuming operation... new MyThread();t.start();
- Inherit the thread class, overwriting the run () method.
- Create a thread object and start the thread with the start () method.
Interview questions
- 1) What is the difference between threads and processes?
A process is a standalone (self contained) operating environment that can be viewed as a program or an application. A thread is a task that executes in a process. A thread is a subset of processes, a process can have many threads, and each thread performs different tasks in parallel. Different processes use different memory spaces, and all threads share the same amount of memory space. Don't confuse it with stack memory, each thread has a separate stack of memory to store local data.
- 2) How do I implement threads in Java?
There are two ways of creating a thread:
First, inherit the thread class and extend the threads.
Second, realize the Runnable interface.
- 3) What is the difference between the start () and run () methods in the Thread class?
Calling the start () method starts the new thread, and if you call the thread's run () method directly, it behaves like a normal method; In order to execute our code in a new thread, you must use the Thread.Start () method.
Extended
Android interface Handlerthread inherits the thread, which is a thread that can use Handler, one that has a message loop. The run () method creates a message queue through Looper.prepare (), which enables the message loop through Looper.loop (). You can perform time-consuming tasks in the run () method, while Handlerthread internally creates a message queue outside the Handler to notify Handlerthread to perform a specific task; the Handlerthread run () method is an infinite Loop, which can terminate the execution of a thread through its quite () or quitsafely () method;
Second, realize the Runnable interface.
public class demoactivity extends baseactivity implements runnable { @Override public void oncreate ( Bundle savedinstancestate) {super . OnCreate (savedinstancestate); Thread T = new Thread (this ); T.start (); } @Override public void run () {}}
Interview questions
- 1) using Runnable or Thread?
We all know that threading can be implemented either by inheriting the thread class or by calling the Runnable interface, and the question is, which is the better way to create a thread? Under what circumstances should it be used? This question is easy to answer if you know that Java does not support multiple inheritance of classes, but allows you to invoke multiple interfaces. So if you're going to inherit other classes, of course it's better to call the Runnable interface.
- 2) What is the difference between Runnable and callable?
Both Runnable and callable represent tasks that you want to perform in different threads. Runnable from the JDK1.0 began, callable is in the JDK1.5 increase. The main difference is that the callable call () method can return a value and throw an exception, while the Runnable run () method does not have these features. The callable can return a future object loaded with calculated results.
Note: This second side of the question is mainly to lead to the following extension, forgive me for this embarrassing appearance.
Extended
First look at the source code of Runnable and callable
publicinterface Runnable { publicvoidrun();}publicinterface Callable<V> { throws Exception;}
Can be drawn:
1) The method under the callable interface is call (), and the Runnable interface is run ().
2) callable can return a value after a task is executed, and Runnable's task cannot return a value.
3) The call () method can throw an exception, and the run () method is not possible.
4) Run the callable task to get a future object that represents the result of an asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the completion of the calculation, and to retrieve the results of the calculation. The future object enables you to understand task execution, cancel the execution of a task, and get execution results.
But, but, everything has but ...
Using callable alone cannot be used with new thread approached (Runnable R), the Thread class only supports Runnable. However, callable can use Executorservice (and throw a concept that will be described in the thread pool of the next article).
It also mentions the future, look at the future interface:
publicinterface Future<V> { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;}
The future defines 5 methods:
1) Boolean cancel (Boolean mayinterruptifrunning): An attempt was made to cancel execution of this task. If the task is completed, canceled, or cannot be canceled for some other reason, the attempt will fail. When cancel () is called, if the call succeeds and the task has not been started, the task will never run. If the task is already started, the mayinterruptifrunning parameter determines whether the thread that performs this task should be interrupted in a way that attempts to stop the task. After this method returns, subsequent calls to IsDone () will always return true. If this method returns true, subsequent calls to iscancelled () will always return true.
2) Boolean iscancelled (): Returns True if the task is canceled before it is properly completed.
3) Boolean isDone (): Returns True if the task is completed. This method returns true in all of these cases, possibly due to a normal termination, exception, or cancellation.
4) V get () throws Interruptedexception,executionexception: Wait for the calculation to complete if necessary, and then obtain the result.
5) V Get (long timeout,timeunit unit) throws Interruptedexception, Executionexception, timeoutexception: If necessary, Wait up to the time that the calculation is given to complete, and obtain its results if the results are available.
It seems that the future interface can not be used in the thread, how to use, who realized the future interface? Answer: Futuretask.
publicclass FutureTask<V> implements RunnableFuture<V> { ...}publicinterface RunnableFuture<V> extends Runnable, Future<V> { void run();}
Futuretask realizes the Runnable and the future, so both the advantages of both can be used in Thread and can be used in Executorservice.
After reading the above-mentioned introduction, let's look at the specific use of the example:
callable<string> callable = new Callable<string> () { @Override public String call () throws Exception {return "callable use" ; }}; futuretask<string> task = new futuretask<string> (callable); Thread T = new Thread (Task); T.start (); //start thread task.cancel (true ); //Cancel thread
The advantage of using Futuretask is that Futuretask is designed to compensate for the lack of thread, which allows the programmer to know exactly when the thread is executing and gets the results returned after the thread execution is complete. Futuretask is an asynchronous computational task that can be canceled, and its calculation is implemented by callable, which is equivalent to Runnable that can carry the result, and has three states: Wait, run, and finish. Completion includes all calculations ending in any way, including normal ends, cancellations, and exceptions.
Thread state
-
New state: A new Thread object was created.
-
Ready state (Runnable): After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used.
-
Running state (Running): The ready state of the thread gets the CPU and executes the program code.
-
Blocking state (Blocked): The blocking state is a temporary stop when the thread abandons the CPU usage for some reason. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking:
(i), waiting for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool.
(ii), synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread.
(iii), other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.
-
Dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.
?
?
Multithreaded
The concept of multithreading is very good understanding is that multiple threads exist at the same time, but to use good multithreading is not easy, involving multi-threaded communication, multi-thread sharing a resource and many other problems.
Advantages and disadvantages of using multithreading:
Advantages:
1) Improve the execution efficiency of the program (simultaneous execution of multiple threads).
2) Appropriate increase in resource utilization (CPU, memory, etc.).
Disadvantages:
1) occupy a certain amount of memory space.
2) The more threads the CPU is, the greater the scheduling overhead.
3) The complexity of the program will increase.
Below I mainly listed some multi-threaded technical points.
Synchronized
Synchronization block Everyone is more familiar with the Synchronized keyword to achieve, all add synchronized method and block statement, when the multi-threaded access, at the same time only one thread can access.
Wait (), notify (), Notifyall ()
These three methods are the final native method of Java.lang.Object, and any class that inherits Java.lang.Object has these three methods. They are the underlying mechanism provided by the Java language to implement inter-threading blocking and control in-process scheduling, which we rarely use at times.
Wait ():
Causes the thread to enter a wait state until it is awakened by another thread through notify () or Notifyall, which can only be called in a synchronous method.
Notify ():
Randomly selects a thread that calls the wait method on the object, unblocking its blocking state, which can only be called inside a synchronous method or synchronous block.
Notifyall ():
All those threads that call the wait method on the object are unblocked, and the method can be called only within the synchronization method or synchronization block.
Wait (), notify (), Notifyall () are instance methods of object. As with each object has a lock, each object can have a list of threads that they wait for from that signal (notification). The thread obtains this waiting list by executing the Wait () method on the object. From that point on, it no longer executes any other instructions until the Notify () method of the object is called. If multiple threads are waiting on the same object, only one thread (not guaranteed in what order) will be selected to continue execution. If no threads are waiting, no special action is taken.
Call any of these three methods, the current thread must be the holder of the lock, and if it does not throw a illegalmonitorstateexception exception.
The difference between wait () and thread.sleep (long time)
Sleep (): Allows the currently executing thread to hibernate (suspend execution) for a specified number of milliseconds without losing ownership of any monitor, and sleep () is a static method dedicated to the thread class for a particular thread.
The wait () method suspends the execution of the thread in the entity, causing the object to enter a wait state until the wait time of the Notify () method notification or wait () is reached. The sleep () method suspends the thread that is held to run, causing the thread to hibernate until the time of hibernation or sleep is interrupted by the interrupt method.
The wait () method releases the synchronization lock when it enters the waiting state, and the sleep () method does not release the synchronization lock. So, when there is no one to interrupt it when a thread has infinite sleep, the program is in great Trouble, notify () is used to inform the thread, but the thread needs to get lock before notify (). Another meaning must be written in synchronized (Lockobj) {...}. Wait () is also the case where a thread needs to release a lock, and it can be freed only if it obtains lock, so wait () also needs to be placed in synchronized (Lockobj) {...}.
volatile keyword
Volatile is a special modifier that can only be used by member variables. Multithreaded operations on member variables are transparent to other threads in the absence of a synchronization class for Java concurrency programs. The volatile variable guarantees that the next read operation will occur after the previous write operation. The thread will read the variable directly from memory and does not cache it. This ensures that the variables read by the thread are consistent with the memory.
ThreadLocal variable
ThreadLocal is a special variable in Java. Each thread has a ThreadLocal that each thread has its own independent variable, and the race condition is completely eliminated. If you provide a copy of your own unique variables for each thread, you will be much more efficient. First, it reduces the number of expensive objects created by multiplexing. Second, you get thread safety without using high-cost synchronization or immutability.
Join () method
The join () method is defined in the thread class, so the caller must be a thread, and the join () method is basically to get the thread that invokes the method to complete the contents of the run () method, then execute the code after the join () method, and look at the following "meaning" code:
new Thread(计数线程一); new Thread(计数线程二); t1.start(); // 等待计数线程一执行完成,再执行计数线程二t2.start();
After starting T1, the Join () method is called until the count task of T1 ends, the T2 starts, and then T2 starts counting tasks, and two threads are executed in strict order. If the execution of T2 depends on the complete data in T1, this method can ensure the synchronization of the two threads well.
Thread.yield () method
Thread.Sleep (long): Thread temporarily terminates execution (sleep) for a certain amount of time.
Thread.yield (): The thread discards the run, yields control of the CPU, pauses the currently executing thread object, and executes other threads.
Both of these methods will give the CPU control of the current running thread, but the sleep () method will not be able to get a running chance in the specified sleep time until its sleep time is complete, and the yield () method gives out control, it is possible to be immediately selected to run by the system scheduling mechanism, for example, The thread that executes the yield () method takes precedence over other threads, and the thread may not have the effect of giving up control of the CPU even if the yield () method is executed, since it gives control and enters the queued queue, The scheduling mechanism will select one of the highest-ranked threads from the queue waiting to run, and it is (probably) selected to run.
Extended
Thread Scheduling Policy
(1) Preemptive scheduling strategy
The thread scheduling algorithm for the Java Runtime system is preemptive. The Java runtime system supports a simple fixed-priority scheduling algorithm. If a thread that has a higher priority than any other thread that is in a running state is in a ready state, the runtime chooses that thread to run. The new higher-priority thread preempted the other threads. However, the Java runtime system does not preempt the same priority thread. In other words, the Java Runtime system is not time-sharing. However, the implementation system based on the Java thread class may support ticks, so do not rely on ticks when writing code. The thread scheduler takes a simple, non-preemptive, round-robin scheduling sequence when the ready-to-use threads in the system have the same priority.
(2) Time-slice rotation scheduling strategy
The thread scheduling of some systems adopts time slice rotation scheduling strategy. This scheduling strategy is to select the highest-priority thread from all the threads in the ready state to allocate a certain amount of CPU time to run. Select another thread to run after that time. A low-priority thread will only be able to execute if the thread is running to end, give up (yield), or get into a blocking state for some reason. If two threads with the same priority are waiting for the CPU, the scheduler selects the running thread in a round-robin fashion.
Synchronization and locking of threads
1, the principle of the lock
Each object in Java has a built-in lock
When the program runs to a non-static synchronized synchronization method, the lock associated with the current instance (this instance) of the executing code class is automatically obtained. Acquiring a lock on an object is also known as acquiring a lock, locking an object, locking on an object, or synchronizing on an object.
The object lock does not work until the program runs to the synchronized synchronization method or code block.
An object has only one lock. Therefore, if a thread obtains the lock, no other thread can get the lock until the first thread releases (or returns) the lock. This also means that no other thread can enter the synchronized method or block of code on the object until the lock is freed.
A release lock is a lock thread that exits the synchronized synchronization method or code block.
For lock and Sync, here are a few points:
1), can only synchronize methods, but not synchronization variables and classes;
2), each object has only one lock; when it comes to synchronization, what should be clearly synchronized? In other words, on which object is it synchronized?
3), you do not have to synchronize all the methods in the class, the class can have both synchronous and non-synchronous methods.
4), if two threads are going to execute the synchronized method in a class, and two threads use the same instance to invoke the method, only one thread can execute the method at a time, and the other waits until the lock is freed. That is, if a thread obtains a lock on the object, no other thread can enter any one of the synchronization methods in the class (the object).
5), if the thread has synchronous and non-synchronous methods, the non-synchronous method can be freely accessed by multiple threads without being restricted by the lock.
6), when the thread sleeps, any locks it holds will not be released.
7), threads can obtain multiple locks. For example, a synchronous method that invokes another object in a synchronous method of an object acquires a synchronization lock for two objects.
8), synchronization damage concurrency, should be as narrow as possible synchronization range. Synchronization can not only synchronize the entire method, but also synchronize some of the code blocks in the method.
9), when using synchronous code blocks, you should specify which object to synchronize on, that is, which object to get the lock. For example:
publicintfix(int y) { synchronized (this) { x = x - y; } return x; }
Of course, synchronous methods can also be rewritten as non-synchronous methods, but functionally identical, for example:
publicsynchronizedintgetX() { return x++; }
And
publicintgetX() { synchronized (this) { return x; } }
The effect is exactly the same.
static method Synchronization
To synchronize a static method, you need a lock for the entire class object, which is the Class (Xxx.class).
For example:
publicstaticsynchronizedintsetName(String name){ Xxx.name = name;}
Equivalent to
publicstaticintsetName(String name){ synchronized(Xxx.class){ Xxx.name = name; }}
What happens if a thread can't get a lock?
If a thread attempts to enter the synchronization method and its lock is already occupied, the thread is blocked on the object. Essentially, a thread enters a pool of that object, where it must wait until its lock is freed and the thread becomes operational or running again.
When considering blocking, be sure to note which object is being used for locking:
1. Threads that call non-static synchronization methods on the same object will block each other. If it is a different object, each thread has its own lock on the object, and the threads do not interfere with each other.
2. Threads that call static synchronization methods in the same class will block each other, and they are all locked on identical class objects.
3. Static synchronization methods and non-static synchronization methods will never block each other, because static methods are locked on the class object, and non-static methods are locked on the object of the class.
4, for the synchronization of the code block, to see what the object has been used to lock (synchronized the contents of the parentheses behind). Threads that synchronize on the same object block each other, and threads that are locked on different objects will never block each other.
When to synchronize
When multiple threads access mutually exclusive (exchangeable) data, they should be synchronized to protect the data, ensuring that two threads do not modify it at the same time.
For data that can be changed in non-static fields, it is usually accessed using a non-static method.
For data that can be changed in a static field, it is usually accessed using static methods.
Java Learning Web site:
http://www.journaldev.com/
Java Threading and multithreaded tutorials
Java Threading: Concepts and Principles
Finally want to know about the thread pool can look at my personal blog: Java thread pool
Java Threading and multithreading