Java concurrent Programming 75 questions and answer--------steady The algorithm

Source: Internet
Author: User
Tags cas garbage collection mutex readline reserved switches thread class wrapper
1. The difference between the daemon and local threads in Java.

There are two types of threads in Java: The daemon thread (Daemon) and the user thread.

Any thread can be set as a daemon thread and a user thread, by method Thread.setdaemon (bool on); True to set the thread as a daemon, or a user thread. Thread.setdaemon () must be called before Thread.Start (), otherwise the runtime throws an exception.

The difference between the two:
The only difference is to determine when the virtual machine (JVM) is leaving, Daemon is serving other threads, and if all of the user thread has been evacuated, Daemon has no service thread, and the JVM is withdrawn. It is also understood that the daemon thread is a thread created by the JVM (but not necessarily) and that the user thread is a thread created by the program; For example, the garbage collection thread of the JVM is a daemon thread, and when all threads have been evacuated and no more garbage generated, the daemon naturally has nothing to do, When the garbage collection thread is the only remaining thread on the Java virtual machine, the Java virtual opportunity automatically leaves.

Extension: Thread dump prints the threading information, and the thread containing the daemon is the daemon, possibly: the service daemon, the compilation daemon, the daemon monitoring ctrl+break under Windows, the finalizer daemon, Reference processing daemon, GC daemon. 2, the difference between the thread and the process.

A process is the smallest unit in which the operating system allocates resources, and the thread is the smallest unit of operating system scheduling.

A program has at least one process, and a process has at least one thread. 3, what is the context switch in multiple threads.

Multithreading uses CPUs on a group of computers, and when the number of threads is greater than the number of CPUs allocated to the program, the CPU needs to be rotated in order for each thread to have an opportunity to execute. Different thread switches using CPU-occurring switching data are context switches. 4. The difference between deadlock and live lock, deadlock and hunger.

deadlock : refers to two or more than two processes (or threads) in the execution process, as a result of contention for resources caused by a mutual wait for the phenomenon, without external forces, they will not be able to push down.
The necessary conditions for a deadlock to occur:
1. Mutually exclusive conditions: the so-called mutual exclusion is the process at a certain time exclusive resources.
2. Request and Retention conditions: a process that is blocked by requesting resources, retains the resources that have been acquired.
3. Non-deprivation of conditions: the process has acquired resources and cannot be forcibly deprived until the end of use.
4. Cyclic waiting conditions: a process of forming a end-to-end cycle waiting for a resource relationship between several processes.

Live Lock : The task or performer is not blocked, because some conditions are not satisfied, resulting in repeated attempts, failure, attempt, failure.

The difference between a live lock and a deadlock is that the entity in the active lock is constantly changing the state, the so-called "live", while the entity in the deadlock is waiting; the living lock may unlock itself and the deadlock cannot.

starvation : One or more threads are unable to obtain the required resources for a variety of reasons, resulting in a state that cannot be performed.
Causes of starvation in Java:
-High priority threads devour all low priority threads for CPU time.
-the thread is permanently blocked in a state that waits to enter the synchronized block, because the other thread is always able to access the synchronized block continuously before it.
-The thread waits for an object that is itself permanently waiting to be completed, such as the wait method that calls the object, because other threads are always awakened continuously. 5, Java in the use of the thread scheduling algorithm is what.

Adopt the way of time slice rotation. You can set the priority of a thread and map it to the priority above the lower system, if you don't need it, avoid thread starvation. 6, what is the thread group, why is not recommended in Java use.

Threadgroup class, you can put the thread into a group of threads, the thread group can be wired to the object, can also be wired to the group, the group can also be wired, such a structure is similar to the form of a tree.

Why not recommend use. Because the use of a lot of security concerns, there is no specific investigation, if necessary, the use of thread pool is recommended. 7, why use the executor framework. each time the task is created thread new threads () is consuming performance and creating a thread is time-consuming and resource-consuming. The threads created by calling new thread () are not managed, are called wild threads, and can be created indefinitely, and competition among threads can lead to excessive system resource consumption and system paralysis, and frequent alternating between wire can consume a lot of system resources. Threads that start with new thread () are not conducive to scaling, such as timed execution, periodic execution, timed execution, thread interrupts, and so on. 8. The difference between executor and executors in Java.

The different methods of the Executors tool class create different thread pools to meet the needs of the business according to our requirements.
The Executor interface object can perform our thread task.
The Executorservice interface inherits the executor interface and expands it, providing more ways to get the status of the task execution and to get the return value of the task.
Use Threadpoolexecutor to create a custom thread pool.
Future represents the result of an asynchronous computation, providing a way to check whether the calculation is complete, waiting for the calculation to complete, and using the Get () method to obtain the result of the calculation. 9. How to find out which thread is using the longest CPU time on Windows and Linux.

Reference:
Http://daiguahub.com/2016/07/31/%E4%BD%BF%E7%94%A8jstack%E6%89%BE%E5%87%BA%E6%B6%88%E8%80%97CPU%E6%9C%80%E5%A4 %9a%e7%9a%84%e7%ba%bf%e7%a8%8b%e4%bb%a3%e7%a0%81/ 10, what is atomic operation. What are the atomic classes (atomic classes) in the Java Concurrency API.

Atomic operation (atomic operation) means "one or a series of operations that cannot be interrupted."
The processor implements atomic operations between multiprocessor using a method based on locking the cache or bus.
In Java, atomic operations can be done by locking and looping CAs. CAS operations--compare & Set, or Compare & Swap, now almost all CPU directives support atomic operations for CAs.

Atomic operation is an operational task unit that is not affected by other operations. Atomic operation is a necessary means to avoid data inconsistency in a multithreaded environment.
Int++ is not an atomic operation, so when one thread reads its value and adds 1 o'clock, another thread might read the previous value, which raises an error.
To solve this problem, it is necessary to ensure that the increase is atomic, and we can use synchronization technology to do this before JDK1.5. The Jdk1.5,java.util.concurrent.atomic package provides an int and a long type of atomic wrapper classes that automatically guarantee that their operations are atomic and do not need to use synchronization.

Java.util.concurrent This package provides a set of atomic classes. Its basic feature is that in a multithreaded environment, when more than one thread executes a method of an instance of these classes at the same time, it is exclusive, that is, when a thread enters a method, executes its instructions, is not interrupted by another thread, and the other thread, like a spin lock, waits until the method executes. It is only a logical understanding that the JVM chooses one other thread from the waiting queue to enter.

Atomic class: Atomicboolean,atomicinteger,atomiclong,atomicreference
Atomic arrays: Atomicintegerarray,atomiclongarray,atomicreferencearray
Atomic Property Update: Atomiclongfieldupdater,atomicintegerfieldupdater,atomicreferencefieldupdater
The atomic class that solves the ABA problem: atomicmarkablereference (by introducing a Boolean to reflect that the middle has not changed), Atomicstampedreference (by introducing an int to reflect whether there has been a change in the middle) 11, what is the Lock interface (lock interface) in the Java concurrency API. What is the advantage of comparing synchronization with it?

The lock interface provides a more extensible lock operation than the synchronization method and the synchronization block.
They allow more flexible structures, can have completely different properties, and can support conditional objects for multiple related classes.

It has the advantage of being able to make the lock more equitable so that the thread can respond to interrupts while waiting for the lock, allowing the thread to attempt to acquire the lock, returning immediately when the lock is not available, or waiting for a period of time to acquire and release the lock in a different order in a different range.

As a whole, lock is an extended version of synchronized, and lock provides unconditional, polling (Trylock method), timed (Trylock with parametric methods), interruptible (lockinterruptibly), and multiple-conditional queues ( Newcondition method) lock operation. In addition, lock's implementation class basically supports the unfair lock (default) and the fair lock, the synchronized only supports the unjust lock, of course, in most cases, the unfair lock is the efficient choice. 12, what is the executors framework.

The executor framework is a framework for asynchronous tasks that are invoked, dispatched, executed, and controlled according to a set of execution policies.

An unlimited creation thread can cause an application memory overflow. So creating a thread pool is a better solution because you can limit the number of threads and recycle the threads. The executors framework makes it easy to create a thread pool. 13, what is the blocking queue. What is the principle of the blocking queue implementation. How to use blocking queues to implement the producer-consumer model.

A blocking queue (Blockingqueue) is a queue that supports two additional operations.

The two additional actions are that when the queue is empty, the thread that gets the element waits for the queue to become non-null. When the queue is full, the thread that stores the elements waits for the queue to be available.

Blocking queues are often used by producers and consumers, and producers are threads that add elements to the queue, and consumers are the threads that take elements from the queue. A blocking queue is a container in which the producer stores elements, and the consumer takes only the elements from the container.

The JDK7 provides 7 blocking queues. respectively:
Arrayblockingqueue: A bounded blocking queue consisting of an array structure.
Linkedblockingqueue: A bounded blocking queue consisting of a list structure.
Priorityblockingqueue: An unbounded blocking queue that supports priority sorting.
Delayqueue: An unbounded blocking queue implemented using a priority queue.
Synchronousqueue: A blocking queue that does not store elements.
LinkedTransferQueue: An unbounded blocking queue consisting of a list structure.
Linkedblockingdeque: A two-way blocking queue consisting of a linked list structure.

Java 5 Implementation of synchronous access before, you can use a common set, and then in the use of thread collaboration and thread synchronization can realize the producer, consumer model, the main technology is to use good, wait, notify,notifyall,sychronized these keywords. After Java 5, you can use the blocking queue to achieve, this way greatly reduced the amount of code, making multithreaded programming easier, security is also guaranteed.
The Blockingqueue interface is a sub-interface of the queue, and its primary purpose is not as a container, but as a thread-synchronized tool, so he has an obvious feature that when a producer thread tries to put an element into the Blockingqueue, the thread is blocked if the queue is full. When a consumer thread tries to remove an element from it, if the queue is empty, the thread is blocked, because it has this attribute, so that multiple threads in the program alternately add elements to the blockingqueue and take out the elements, which can well control the communication between threads.

The most classic scenario for blocking queues is to read and parse the socket client data, and the thread that reads the data keeps the data in the queue, and then parses the thread from the queue to parse the data continuously. 14, what is callable and future?

The callable interface is similar to the runnable, it can be seen from the name, but Runnable will not return the result, and can not throw the return of the result of the exception, and the callable function is more powerful, after the thread executes, can return the value, this return value can be future to get , which means that future can get the return value of the asynchronous execution task.
It can be thought of as a runnable with callbacks.

The future interface represents the asynchronous task, which is the future result of a task that has not yet been completed. So callable is used to produce results, future are used to obtain results. 15, what is Futuretask? Use Executorservice to start a task.

In a Java concurrency program, Futuretask represents an asynchronous operation that can be canceled. It has the methods of starting and canceling operations, whether the query operation is completed and the result of retrieving the operation. The result can be retrieved only when the operation is complete, and the Get method will block if the operation has not yet been completed. A Futuretask object can be wrapped over an object that invokes callable and runnable, and because Futuretask also invokes the Runnable interface, it can be submitted to executor for execution. 16, what is the implementation of concurrent containers.

What is a synchronization container: a container that can be simply understood to implement synchronization through synchronized, if more than one thread invokes the method of the synchronization container, they are executed serially. such as Vector,hashtable, and Collections.synchronizedset,synchronizedlist and other methods return the container.
By looking at the implementation code for these synchronization containers, such as vector,hashtable, you can see that these containers are thread-safe by encapsulating their states and adding keyword synchronized to the methods that need to be synchronized.

The concurrency container uses a completely different locking strategy than the synchronization container to provide higher concurrency and scalability. For example, in Concurrenthashmap, a finer granularity locking mechanism, which can be called a segmented lock, allows any number of read threads to access the map concurrently. And the thread that performs the read operation and the write thread can also access the map concurrently, allowing a certain number of write-operation threads to modify the map concurrently, so that it can achieve higher throughput in concurrent environments. 17, multithreading synchronization and mutual exclusion there are several ways to achieve, are what.

Thread synchronization is a constraint relationship between threads, and the execution of one thread relies on messages from another thread and waits when it does not get messages from another thread until the message arrives.
Thread mutex refers to the exclusive nature of the shared process system resources that are accessed by individual threads. When a shared resource is used by several threads, at any time only one thread is allowed to use it, other threads that want to use the resource must wait until the resource is freed by the resource. A thread mutex can be considered a special kind of thread synchronization.

The synchronization methods between threads can be divided into two categories: User mode and kernel mode. As the name suggests, kernel mode refers to the use of the system kernel object of the single to synchronize, the use of the need to switch between the kernel State and user state, and user mode is not required to switch to the kernel state, only in the user state to complete the operation.
The methods in user mode are: atomic operation (e.g. a single global variable), critical region. The methods in kernel mode are: event, semaphore, mutex. 18, what is the competitive conditions. How you find and solve competition.

When multiple processes attempt to do something with shared data, and the final result depends on the order in which the process is run, we think that there is a competitive condition (race condition). 19, how you will use thread dump. How you will analyze thread dump.

new State (new)
The thread created with the new statement is in the new state, and it is just like other Java objects that are allocated memory only in the heap area. Ready Status (Runnable)
When a thread object is created, the other thread calls its start () method, and the thread enters the ready state, and the Java virtual Opportunity creates a method call stack and program counter for it. The thread in this state is in the runtime pool, waiting for the right to use the CPU. Run status (Running)
Threads in this state occupy the CPU and execute program code. Only threads in the ready state have an opportunity to go to run state. blocking status (Blocked)
A blocking state is a thread that discards the CPU for some reason and temporarily stops running. When a thread is blocked, the Java Virtual Machine does not allocate a CPU to the thread. Until the thread is back in the ready state, it has the opportunity to go to the running state.
The blocking state can be divided into the following 3 types:
Blocking state in object waiting pool (Blocked in object ' s wait Pool): When a thread is running, if the Wait () method of an object is executed, the Java virtual machine puts the thread into the waiting pool of the object, which involves the contents of the thread communication. The blocking state in the object lock pool (Blocked in object ' lock Pool): When a thread is running, trying to get a sync lock on an object, if the synchronization lock of the object is already occupied by another thread, the Java virtual machine puts the thread in the lock pool of the object. This involves the contents of "Thread synchronization." Other blocking states (otherwise Blocked): The current thread executes the sleep () method, or when the join () method of another thread is invoked, or when an I/O request is made, it enters this state. State of Death (Dead)
When the thread exits the run () method, it enters the death state, which ends the lifecycle.

We run the deadlock code before the Simpledeadlock.java, and then try to output the information (/* This is the annotation, the author himself added * *):

/* Time, JVM information/2017-11-01 17:36:28 full thread dump Java HotSpot (TM) 64-bit Server VM (25.144-b01 mixed mode):/* Thread Name: De STROYJAVAVM Number: #13 Priority: 5 System Priority: 0 JVM Internal thread id:0x0000000001c88800 corresponding system thread ID (nativethread ID): 0X1C18 thread state: Waiting on condition [0x0000000000000000] (Waiting for a condition) thread detail status: Java.lang.Thread.State:RUNNABLE and then all * * "DESTROYJAVAVM" #13 prio=5 os_p Rio=0 tid=0x0000000001c88800 nid=0x1c18 waiting on condition [0x0000000000000000] Java.lang.Thread.State:RUNNABLE "Th Read-1 "#12 prio=5 os_prio=0 tid=0x0000000018d49000 nid=0x17b8 waiting for monitor entry [0x0000000019d7f000]/* thread state: Blocking (in Object sync) code location: at Com.leo.interview.simpledeadlock$b.run (simpledeadlock.java:56) wait for Lock: 0x00000000d629b4d8 has acquired lock: 0x 00000000d629b4e8*/Java.lang.Thread.State:BLOCKED (on object monitor) at Com.leo.interview.simpledeadlock$b.run (Si mpledeadlock.java:56)-Waiting to lock <0x00000000d629b4d8> (a java.lang.Object)-locked <0x00000000d62 9b4e8> (a java.lang.Object) "Thread-0 "#11 prio=5 os_prio=0 tid=0x0000000018d44000 NID=0X1EBC waiting for monitor entry [0x000000001907f000] Java.lang . Thread.State:BLOCKED (on object Monitor) in Com.leo.interview.simpledeadlock$a.run (simpledeadlock.java:34)-Wait

ing to lock <0x00000000d629b4e8> (a java.lang.Object)-locked <0x00000000d629b4d8> (a java.lang.Object) Service Thread #10 daemon prio=9 os_prio=0 tid=0x0000000018ca5000 nid=0x1264 runnable [0x0000000000000000] Java.lang. Thread.State:RUNNABLE "C1 CompilerThread2" #9 daemon prio=9 os_prio=2 tid=0x0000000018c46000 nid=0xb8c waiting on Condit Ion [0x0000000000000000] Java.lang.Thread.State:RUNNABLE "C2 CompilerThread1" #8 daemon prio=9 os_prio=2-tid=0x000000 0018be4800 nid=0x1db4 waiting on condition [0x0000000000000000] Java.lang.Thread.State:RUNNABLE "C2 CompilerThread0" #7 Daemon prio=9 os_prio=2 tid=0x0000000018be3800 nid=0x810 waiting on condition [0x0000000000000000] java.lang.Thread. State:runnable "Monitor ctrl-break "#6 daemon prio=5 os_prio=0 tid=0x0000000018bcc800 nid=0x1c24 runnable [0x00000000193ce000] Java.lang.Thr ead. State:runnable at Java.net.SocketInputStream.socketRead0 (Native method) at Java.net.SocketInputStream.socketRead ( socketinputstream.java:116) at Java.net.SocketInputStream.read (socketinputstream.java:171) at Java.net.SocketInput Stream.read (socketinputstream.java:141) at Sun.nio.cs.StreamDecoder.readBytes (streamdecoder.java:284) at SUN.NIO.C  S.streamdecoder.implread (streamdecoder.java:326) at Sun.nio.cs.StreamDecoder.read (streamdecoder.java:178)-locked <0x00000000d632b928> (a Java.io.InputStreamReader) at Java.io.InputStreamReader.read (Inputstreamreader.java : 184) at Java.io.BufferedReader.fill (bufferedreader.java:161) at Java.io.BufferedReader.readLine (Bufferedreader.ja va:324)-Locked <0x00000000d632b928> (a java.io.InputStreamReader) at Java.io.BufferedReader.readLine (Buffe
    redreader.java:389)At Com.intellij.rt.execution.application.appmainv2$1.run (appmainv2.java:64) "Attach Listener" #5 daemon prio=5 Os_ prio=2 tid=0x0000000017781800 nid=0x524 runnable [0x0000000000000000] Java.lang.Thread.State:RUNNABLE "Signal DISPATC Her "#4 daemon prio=9 os_prio=2 tid=0x000000001778f800 nid=0x1b08 waiting on condition [0x0000000000000000] Java.lang.T Hread. State:runnable "Finalizer" #3 daemon prio=8 os_prio=1 tid=0x000000001776a800 Nid=0xdac in object.wait () [0x0000000018b6f ] Java.lang.Thread.State:WAITING (on object Monitor) in Java.lang.Object.wait (Native method)-Waiting On & Lt;0x00000000d6108ec8> (a java.lang.ref.referencequeue$lock) at Java.lang.ref.ReferenceQueue.remove ( referencequeue.java:143)-Locked <0x00000000d6108ec8> (a java.lang.ref.referencequeue$lock) at Java.lang.re F.referencequeue.remove (referencequeue.java:164) at Java.lang.ref.finalizer$finalizerthread.run (Finalizer.java : 209) "Reference Handler" #2 daemon prio=10 Os_prio=2 tid=0x0000000017723800 nid=0x1670 in object.wait () [0x00000000189ef000] Java.lang.Thread.State:WAITING (on Obje CT monitor) at Java.lang.Object.wait (Native method)-Waiting on <0x00000000d6106b68> (a Java.lang.ref.Refer Ence$lock) at java.lang.Object.wait (object.java:502) at java.lang.ref.Reference.tryHandlePending (reference.java:19 1)-Locked <0x00000000d6106b68> (a java.lang.ref.reference$lock) at Java.lang.ref.reference$referencehandle R.run (reference.java:153) "VM Thread" os_prio=2 tid=0x000000001771b800 nid=0x604 runnable "GC task thread#0 (PARALLELGC ) "Os_prio=0 tid=0x0000000001c9d800 nid=0x9f0 runnable" GC task thread#1 (PARALLELGC) "Os_prio=0 tid=0x0000000001c9f000 NID=0X154C runnable "GC task Thread#2 (PARALLELGC)" Os_prio=0 tid=0x0000000001ca0800 nid=0xcd0 runnable "GC Task Threa D#3 (PARALLELGC) "Os_prio=0 tid=0x0000000001ca2000 nid=0x1e58 runnable" VM periodic Task Thread os_prio=2 tid=0x0000000 018c5a000 Nid=0x1b58 WaiTing on condition JNI Global references:33/* The information about deadlocks can be seen here. */Found One java-level deadlock: ============================= "Thread-1": Waiting to lock monitor 0x0000000017729fc8 ( Object 0x00000000d629b4d8, a java.lang.Object), which is held by ' Thread-0 ' "Thread-0": Waiting to lock monitor 0x0000 000017727738 (Object 0x00000000d629b4e8, a java.lang.Object), which is held by ' Thread-1 ' Java stack information for th E threads listed above: =================================================== "Thread-1": at Com.leo.interview.SimpleDe Adlock$b.run (simpledeadlock.java:56)-Waiting to lock <0x00000000d629b4d8> (a java.lang.Object)-locked &L T;0x00000000d629b4e8> (a java.lang.Object) "Thread-0": At Com.leo.interview.simpledeadlock$a.run ( simpledeadlock.java:34)-Waiting to lock <0x00000000d629b4e8> (a java.lang.Object)-locked <0x00000000d

629b4d8> (a java.lang.Object) Found 1 deadlock.     /* Memory usage, details to see the JVM book/Heap Psyounggen Total 37888K, used 4590K [0x00000000d6100000, 0x00000000d8b00000, 0x0000000100000000] Eden space 32768K, 14% used [0x00 000000d6100000,0x00000000d657b968,0x00000000d8100000) from space 5120K, 0% used [0x00000000d8600000, 0x00000000d8600000,0x00000000d8b00000) to space 5120K, 0% used [0x00000000d8100000,0x00000000d8100000,
  0x00000000d8600000) Paroldgen total 86016K, used 0K [0x0000000082200000, 0x0000000087600000, 0x00000000d6100000] Object Space 86016K, 0% used [0x0000000082200000,0x0000000082200000,0x0000000087600000) metaspace used 3474K, Capac  ity 4500K, committed 4864K, reserved 1056768K class space used 382K, capacity 388K, committed 512K, reserved 1048576K
20. Why we run the Run () method when we call the start () method, why we can't call the run () method directly.

When you call the start () method, you create a new thread and execute the code in the Run () method.
But if you call the run () method directly, it will not create a new thread or execute the code of the calling thread, it will only execute the Run method as a normal method. 21. How do you wake up a blocked thread in Java?

In the Java development history, the suspend () and resume () methods were used to wake the thread for blocking, but there were many problems, the typical deadlock problem.
The solution can use an object-targeted blocking, that is, the wait () and notify () methods of the object class are used to implement thread blocking.
First, the wait, notify method is for the object, and the Wait () method that invokes any object will cause the thread to block, blocking the lock of the object, and, correspondingly, calling the Notify () method of any object will randomly dismiss the thread that blocked the object. But it needs to regain the lock on the modified object until it succeeds, and secondly, the wait, notify method must be called in the synchronized Block or method, and to ensure that the lock object of the synchronized block or method is the same as the object calling the wait, notify method. This means that the current thread has successfully acquired a lock on an object before the wait is invoked, and when the wait is blocked, the line is freed from the previously acquired object lock. 22, in Java Cyclibarriar and countdownlatch what is the difference.

Cyclicbarrier can be reused, and countdownlatch cannot be reused.
Java concurrent package inside the Countdownlatch can actually think of it as a counter, but the operation of this counter is atomic operation, at the same time only one thread to operate the counter, that is, at the same time only one thread to reduce the value of this counter.
You can set an initial number for the Countdownlatch object to count, and any await () method that invokes the object will block until the counter's count is reduced to 0 by the other thread.
So before the current count reaches 0, the await method will remain blocked. After that, all waiting threads are freed and all subsequent calls to the await are returned immediately. This phenomenon occurs only once--the count cannot be reset. If you need to reset the count, consider using Cyclicbarrier.
A very typical scenario for Countdownlatch is that you have a task that you want to perform down, but you have to wait until the other task has finished executing before you can proceed down. If the task we want to continue to execute calls a Countdownlatch object's await () method, and the other task finishes its own task, invokes the countdown () method on the same Countdownlatch object, which await () The task of the method blocks the wait until the count of the Countdownlatch object is reduced to 0.

Cyclicbarrier a synchronization helper class that allows a set of threads to wait on each other until it reaches a public barrier point (common barrier). In programs that involve a set of fixed-size threads, these threads have to wait for each other at times, and Cyclicbarrier is useful at this time. Because the barrier can be reused after releasing the wait thread, it is called the barrier of the loop. 23, what is immutable object, it to write concurrent application what help.

An immutable object (immutable Objects) is an object that cannot be changed once it is created (the object's data, or the object's property value), or a mutable object (mutable Objects).
The class of immutable objects is immutable (immutable Class). The Java Platform Class Library contains a number of immutable classes, such as String, base-type wrapper class, BigInteger, and BigDecimal.
Immutable objects are inherently thread-safe. Their constants (fields) are created in the constructor. Since their state cannot be modified, these constants will never change.

Immutable objects are always thread-safe.
An object is immutable only if it satisfies the following state;
Its state cannot be modified after it has been created;
All domains are final types;
It was created correctly (no escape from this reference occurred during creation). 24, what is the context switch in multiple threads.

During context switching, the CPU stops processing the currently running program and saves the specific location of the current program to continue running. From this perspective, context switching is a bit like when we're reading a few books at the same time, switching books back and forth, we need to remember the page numbers that each book is currently reading. In a program, the "page number" information in the context switch process is stored in the Process Control block (PCB). PCB is also often called "Toggle Frame" (switchframe). The page number information is saved to the CPU's memory until they are used again.
Context switching is the process of storing and recovering a CPU state that enables thread execution to resume execution from a breakpoint. Context switching is a basic feature of multitasking operating systems and multithreaded environments. 25, Java in the use of the thread scheduling algorithm is what.

Computers usually have only one CPU, and only one machine instruction can be executed at any time, and each thread can execute instructions only if it has access to the CPU. The so-called multithreading of concurrent operation, in fact, refers to the macroscopic view, each thread to take turns to get the right to use the CPU, respectively, the implementation of their There will be more than one thread in the ready state waiting for the Cpu,java virtual machine to be responsible for the scheduling of threads, and thread scheduling refers to the use of a specific mechanism for allocating CPU to multiple threads.

There are two kinds of scheduling models: time-sharing scheduling model and preemptive scheduling model.
Time-Sharing scheduling model is to allow all threads to take the right to use the CPU, and evenly allocate each thread occupies CPU time slice this is also better understanding.

The Java Virtual machine uses preemptive scheduling model, which is to prioritize the high priority threads in the runtime to occupy the CPU, if the same thread priority in the runtime pool, then randomly select a thread, so that it occupies the CPU. The running thread runs until it has to abandon the CPU. 26, what is the thread group, why is not recommended in Java use.

Thread groups and threads pools are two different concepts that are completely different in that they are designed to facilitate thread management, which is to manage the lifecycle of threads, to reuse threads, and to reduce the overhead of creating destruction threads. 27. Why using the executor framework is better than creating and managing threads using applications.

Why to use the executor thread pool framework
1. Each time the task is created threads new thread () compared to consuming performance, creating a thread is more time-consuming and resource-intensive.
2, call the new thread () created by the lack of management, called the Wild thread, and can be unlimited to create, the competition between threads will lead to excessive consumption of system resources and cause system paralysis, and the frequent alternating between the wire will also consume a lot of system resources.
3, the direct use of new thread ()-initiated threads are not conducive to expansion, such as scheduled execution, regular execution, scheduled periodic execution, thread interruption, etc. are not easy to achieve.

Advantages of using the executor thread pool framework
1, can reuse existing and idle threads to reduce the creation of thread objects so as to reduce the cost of dying threads.
2, can effectively control the maximum number of concurrent threads, improve system resource utilization, while avoiding excessive resource competition.
3, the frame has a timer, regular, single, concurrent number control functions.
To sum up, use the thread pool framework to executor better manage threads and provide system resource usage. 28, there are several ways to implement a thread in Java. the inheritance thread class implements the callable interface of the Runnable interface, and needs to implement the call () method 29, how to stop a running thread.

How to use shared variables
In this way, a shared variable is introduced because it can be used by more than one thread that performs the same task as a signal of interruption, and the execution of the thread in the notification.

Terminating a thread using the interrupt method
How do you stop a thread if it is blocked by waiting for some event to occur? This happens often, such as when a thread is blocked by the need to wait for keyboard input, or calls the Thread.Join () method, or the Thread.Sleep () method, calls the Serversocket.accept () method on the network. Or when the Datagramsocket.receive () method is invoked, it can cause a thread to block, and when the thread is in a state that is not running, even if the thread's shared variable is set to True in the main program, the thread cannot check the loop flag at all, and of course it cannot be interrupted immediately. The advice here is to not use the Stop () method, but rather to use the interrupt () method provided by thread, which, while not interrupting a running thread, can cause a blocked thread to throw an interrupt exception, which causes the thread to end the blocking state prematurely, Exit blocking code. 30, notify () and Notifyall () what is the difference.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.