Featured topic thread 53

1. What is the thread

A thread is the smallest unit of an operating system capable of operation schedule, which is included in the process, the actual operation of the unit process. Programmers can be programmed via its multi-processor, multi-threading can be used to accelerate compute-intensive tasks. For example, if a thread to complete a task to be 100 ms, then complete the task in just 10 milliseconds changed with ten threads. In the Java language provides a good level of support for multithreading.

 

2. What is the difference between threads and processes

Conceptually:

Process: a program for the implementation of a process of dynamic data set is the basic unit of resource allocation.

Thread: present in the process, it is the basic unit of scheduling in the process. Shared resources processes.

From the point of view the implementation process: Process: an independent memory units, while multiple threads shared memory, thereby improving the operating efficiency of the application. Thread: each individual thread has a running entry, order execution sequence, and exit the program. But the thread of execution can not be independent, it must exist according to the application, providing multiple execution threads controlled by the application.

From a logical point of view :( meaning multithreaded important difference) that an application, there are multiple execution section may execute simultaneously. However, the operating system and multiple threads will not be seen as multiple independent applications to achieve scheduling and management and resource allocation processes.

In short, there is at least one program a process, a process has at least one thread. Process is the basic unit of resource allocation, threads share the process resources.

 

3. How to implement a thread in Java

Thread class inheritance or implement Runnable interface.

 

4. Thread or Runnable

Java does not support multiple inheritance classes, but allows you to call multiple interfaces. So if you want to inherit from other classes, of course, is to achieve Runnable interface better.

 

5.Thread class start () and run () method What is the difference

start () method is used to start a new thread is created, and the start () internally calls the run () method, and this effect directly call run () method is not the same. When you call the run () method will only be invoked in the original thread, no new thread is started, start () method will start a new thread. That is a start method to start a thread, is truly a multi-threaded. The run method just an ordinary method.

 

6.Java in Runnable and Callable What is the difference

Runnable and Callable represent those tasks to be performed in different threads. From the beginning there JDK1.0 Runnable, Callable in JDK1.5 increased. The main difference is the Callable call () method returns a value and throw an exception, but the Runnable run () method do not have these features.

 

7.Java in CyclicBarrier and CountDownLatch What is the difference

They are JUC in class, CyclicBarrier and CountDownLatch can be used to make a set of threads waiting for the other thread. CountdownLatch count difference is not be reset. If you need to reset the count, consider using CyclicBarrier.

 

What 8.Java memory model is

Java memory model rules and guidelines Java programs have definitively behavior between different memory architectures, CPU and operating system. It is particularly important in the case of multi-threaded. Java memory model to change a thread can be made visible to other threads to provide a guarantee, the relationship between them in advance. This relationship defines rules allow programmers in concurrent programming ideas more clearly.

Code within threads to execute in chronological order, which is called a program sequence rules.

For the same before a lock, an unlock operation occurs after another must take place on time lock operation, also known as the tube locking rules.

Before a write operation to the volatile before the read operation after a volatile, also known as volatile variable rules.

After any necessary operations within a thread in this thread's start () call, also known as the thread start rule.

All operations will be a thread before the thread terminates, the thread terminates rules.

End of the operation required an object after the object is constructed, also known as object finalization rules.

 

What is the 9.Java volatile variables

Java language provides a weaker synchronization mechanism that volatile variables. But the volatile container is not completely correct, complete understanding. Generally, volatile includes two semantic, or two characteristics. The first is to ensure that volatile variables for visibility of all threads, visibility here means that when a thread modifies the variable, the new value to other threads can be immediately learned. The common variables can not do this.

Article second semantic command is prohibited reordering optimization, this was only the semantic repair JDK1.5.

On the first point: According to JMM, all variables are stored in the main memory, and each thread also has its own working memory, working memory thread save a copy of a copy of main memory to use the thread variable, the variable in the thread operations for working memory, the main memory can not be directly read and write variables. At this point volatile visibility due to ordinary variables can not be done because of this. For example, thread A modified a common value of the variable, and then written back to main memory, thread B thread A write-back after the completion of the reading from the main memory, a new variable to be visible to thread B. In fact, according to Virtual Machine Specification, volatile variables still have a copy of the working memory, the visibility to be achieved by means of main memory. However, due to special rules volatile guarantee new value can be synchronized back to main memory immediately, and from main memory to refresh each use, in order to ensure the visibility of multi-threaded operating volatile variables.

On the second point: first reordering said instructions, instruction reordering means using a CPU command does not allow multiple points in a predetermined order corresponding to the development processing unit, but does not mean that any rearrangement, CPU processing instructions need to correctly dependent case ensure that the final results are correct reordering instruction is to optimize the operation of the machine level. So why volatile reorder instructions to ban it, but also how to do it. For example, single-mode embodiment the DCL (double check locking) of. Declared volatile, many of the code will be inserted to ensure that the processor memory barrier instructions out of order execution occurs. And because the guarantee Happens-before rule, writes in the earlier example can occur before a subsequent read operation.

In addition to the above two points, volatile to further ensure the long and double 64-bit read are atomic. Virtual machines are allowed in the JMM 64 bit long and double non-volatile read-write operation of a modified 32-bit sub-divided into two to perform the operation, which is a so-called non-atomic agreement long and double.

Based on the above, we know that although these volatile semantics and properties in the case of concurrent still can not guarantee thread safety. Still need to lock in most cases.

Unless the following two conditions:

Operation is not dependent on the current value of the variable, or can be modified to ensure that the value of the variable is only a single thread;

Variables do not need to participate in invariants with other state variables.

 

In 10.Java, writing multithreaded programs when you which will follow the best practices?

Named to the thread, which can help debug.

Minimize synchronization range, rather than the entire way to synchronize, synchronize only do key part.

If you can, prefer to use volatile and not synchronized.

Use a higher level of concurrency utilities, instead of using the wait () and notify () to implement inter-thread communication, such as BlockingQueue, CountDownLatch and Semeaphore.

Priority use concurrent collections, rather than a set of synchronization. Concurrent collections provide better scalability.

 

11. What is thread safe? Vector is a thread-safe class yet

If your code where the process has multiple threads running at the same time, and these threads may run this code at the same time. If the result of each run single-threaded operating results and the same, and also the values ​​of other variables and expectations are the same, that is thread-safe. A thread-safe counter the same instance of an object class will not miscalculations in the case of the use of multiple threads. Obviously you can collection class into two groups, thread-safe and non-thread-safe. Vector is synchronized methods to achieve thread-safe, but it and similar ArrayList is not thread safe.

 

What is 12.Java in race conditions? An example will be described.

Race conditions can cause some bugs in the program of concurrency. Multithreading some resources will have competition when race conditions, if the program fails to execute first competition discharged later executed, then the whole program there will be bugs some uncertain. This is difficult to find bugs and will be repeated, because the random competition between threads. One example is the order processing.

 

13.Java how to stop a thread

When the run () or call () method of executing the thread will automatically end, if you want to end a thread manually, you can use volatile boolean variable to exit the run () method of recycling or cancel the task to interrupt thread. Other circumstances: Exception - Stop the sleep - Stop blocking execution - stop execution

 

14. The run occurs when a thread exception would happen

Simply put, if the exception is not caught the thread will stop executing. Thread.UncaughtExceptionHandler for handling uncaught exceptions caused by a sudden interruption of a thread-line interface. When an uncaught exception will cause disruption JVM thread will use Thread.getUncaughtExceptionHandler () to query the thread and the thread UncaughtExceptionHandler and abnormal passed as parameters to the uncaughtException handler () method for processing.

 

15. How to share data between two threads?

For this purpose, or to use such as blocking queues concurrently shared object through a data structure

 

16.Java in notify and notifyAll What is the difference

notify () method can not wake up a specific thread, so only one thread it have handy while waiting. The notifyAll () wakes up all the threads and allows them to compete for locks to ensure that there is at least one thread can continue to run.

 

17. Why wait, notify, and notifyAll these methods are not inside thread class

One obvious reason is that the lock is JAVA provide object-level and not the thread level. If a thread needs to wait for some lock then call the object wait () method to sense. If the wait () method defined in the Thread class, which thread is waiting for the lock is not obvious. Simply put, because the wait, notify and notifyAll are lock-level operations, so they are defined in the Object class because locks belong to the object.

 

18. What is the ThreadLocal

ThreadLocal, thread-local variables.

When using ThreadLocal variable maintenance, ThreadLocal provided for each thread using the variable independent variable copies, each thread can independently change their copy without affecting other threads corresponding to a copy of the thread is isolated. The secret lies in ThreadLocalMap thread isolation class (ThreadLocal static inner classes)

Thread-local variables are variables limited internal thread, all belonging to the thread itself, among a plurality of threads are not shared. ThreadLocal Java provides classes for thread-local variables, it is a way to achieve thread-safe. However, under the management of the environment (such as a web server) using thread-local variables of time to be especially careful, in this case, the worker's life cycle longer than the life cycle of any application variables. Once any thread local variables is not released after the work is completed, Java applications, there is a risk of memory leaks.

ThreadLocal method: void set (T value), T get () and T initialValue ().

ThreadLocal is how to create a copy of the variable for each thread:

First, there is within each thread Thread ThreadLocal.ThreadLocalMap a member variable of type threadLocals, this threadLocals is used to store a copy of the actual variable value is the current ThreadLocal variable, value for the variable copy (ie, variables of type T). Initially, ThreadLocals empty, when invoked by ThreadLocal variable get () method, or set () method of the Thread class will be initialized in ThreadLocals, ThreadLocal variables and the current key to be saved copy ThreadLocal variables value, to keep threadLocals. Then the current thread inside, if you want to use a copy of the variable, you can look at threadLocals inside by the get method.

to sum up:

ThreadLocal created by an actual copy of each thread is stored in its own threadLocals

Why threadLocals key to ThreadLocal object because each thread can have multiple threadLocal variables, like the above code longLocal and stringLocal;

Before get, you must first set, otherwise it will be reported null pointer exception; no need to call if you want to set before you can get access to normal, it must override initialValue () method

 

19. What is FutureTask?

In concurrent programs in Java FutureTask represents an asynchronous operation can be canceled. It has a start and cancel operations, query and retrieval operation is complete calculation results and other methods. Only when the operation is completed when the results can be retrieved, if the operation has not completed the get method will block. A FutureTask object can be packaged to call Callable and Runnable objects, due FutureTask also called Runnable interface so it can be submitted to the Executor to execute.

 

20.Java difference in the method of interrupted and isInterruptedd

interrupted is a static method, isInterruptedd is a common method

If the current thread is interrupted (without throwing an exception interrupt, or interrupt status is cleared), you call interrupted method returns true for the first time. Then, the current thread's interrupt status is cleared internal method. It will return false when the second call. If you have just started calling isInterrupted, it will always return true, unless the middle thread's interrupt status is cleared up other operations. That isInterrupted simply polling the interrupt state, the state will not be modified.

 

21. Why wait and notify methods to be invoked in the sync blocks

If you do not, the code will throw an exception IllegalMonitorStateException. Another reason is to avoid race conditions between the wait and notify.

 

22. Why should you check in a loop waiting for the conditions?

Thread in a wait state may receive false alarms and spurious wake, if not wait for the cycle to check the conditions, the program will not meet in the case of the end of the exit conditions. Therefore, when a waiting thread wakes up, it can not be considered the original waiting status is still valid, after the method call and notify waiting threads wake up before this time it may change (). This is the use of wait in a loop () method better reasons.

 

Collection and synchronization of concurrent collections 23.Java What is the difference

Concurrent collections are synchronized set of multi-threading and concurrency provide a suitable set of thread-safe is, however, complicated by a collection of higher scalability. Before Java1.5 programmers to use and the only set of synchronization in multithreaded concurrent time can cause contention, hindering the expansion of the system. Java1.5 joined the concurrent collections like ConcurrentHashMap, not only provides thread safety also locks the isolation and internal partitions and other modern technology to improve scalability. Most of them located in the JUC package.

 

24.Java heap and stack What is the difference

Each thread has its own stack memory for storing local variables, method parameters and the call stack, variables stored in a thread on the other thread is not visible. The heap is shared by all threads in a public area of ​​memory. Objects are created on the heap, in order to enhance the efficiency of thread will get from a heap cache to its own stack, it could cause problems if multiple threads use the variable, then the volatile variables come into play, and it requires from the main thread reading stored values ​​of the variables.

 

25. What is the thread pool? Why use it?

To create a thread costly resources and time, if the task was to create a thread so the response time will be longer, and the limited number of threads a process can create. To avoid these problems, when the program started several threads created to respond to treatment, they are called the thread pool, which threads called worker threads. From the beginning JDK1.5, Java API provides the Executor framework allows you to create different thread pool. For example, a single thread pool, each dealing with a task; a fixed number of thread pool thread pool, or cache (for a much shorter survival task program scalable thread pool).

 

26. How to write code to solve the producer-consumer problem?

In reality many threads you solve problems belong to the producer consumer model is a thread production tasks for other threads to consume, you have to know how inter-thread communication to solve this problem. Relatively low-level approach is to use wait and notify to solve this problem, more praise way is to use Semaphore or BlockingQueue to achieve producer-consumer model.

 

27. How to avoid deadlocks?

Deadlock is a phenomenon of two or more processes in the implementation process, a result of competition for resources caused by waiting for each other, in the absence of external force, they will not be able to promote it. This is a serious problem, because the deadlock will make your program hangs task can not be completed, a deadlock occurs following four conditions must be met:

Mutually exclusive conditions: a resource can only be used by a process.

Request to maintain conditions: when a request for due process and resource blocked for resources has been kept tightly.

Not deprivation: Resources process has been in use before the end of the finish, it can not be forcibly deprived.

Loop wait condition: end to end to form a loop waiting for a resource relationship between several processes.

The easiest way to avoid the deadlock is to prevent circular wait condition, will all the resources to set the system flag, sort, process applications require all resources must be in a certain order (ascending or descending) to do the operation to avoid deadlock.

 

Live locks and deadlocks in 28.Java What is the difference?

Live locks and deadlocks similar, except that the lock state is active threads or processes are constantly changing, live lock can be considered a special kind of hunger. Livelock a real world example of two people in a small hallway encounter, two people are trying to avoid each other so that each other through, but because evade are the same no one can lead to last through the corridor. Simply put, livelock and deadlock the main difference is that the former state of the process can be changed but it can not continue.

 

29. how to detect whether a thread has a lock

There is a method called holdsLock () in the java.lang.Thread, it returns true if and only if the current thread has a lock on a specific object.

 

30. How do you get the thread stack in Java

eak key combination to obtain the thread stack, Linux use kill -3 command. You can also use this tool to get jstack, it operates thread id, id with jps you can find this tool.

 

31.JVM memory configuration parameters

1.-Xmx: maximum heap size

2.-Xms: initial heap size (minimum memory value)

3.-Xmn: the size of the young generation

4.-XXSurvivorRatio: 3 means Eden: Survivor = 3: 2

5.-Xss stack capacity

6.-XX: + PrintGC GC log output

7.-XX: + PrintGCDetails output detailed log of GC

 

32.Java in synchronized and what is the difference ReentrantLock

Java in the past for a long period of time can only be achieved through mutual exclusion synchronized keyword, it has some drawbacks. For example, the way you can not extend beyond the lock or block boundaries, try not halfway cancellation acquiring a lock. Java 5 interface provides more sophisticated control by Lock to solve these problems. ReentrantLock class implements Lock, it has synchronized with the same concurrency and memory semantics and it is scalable.

 

33. There are three threads T1, T2, T3, how they are executed in order to ensure

You can join with a thread class () method. Specific operations run method is called T3 in t2.join (), so that re-executing the execution t2 T3; T2 is called the run method t1.join (), and then executing the execution so t1 t2. This sequence T1, T2, T3 is performed

 

yield method 34.Thread class what role

Yield method to pause the currently executing thread object, let the other have the same priority thread. It is a static method and only guarantee the current thread can not give up CPU usage to ensure that other threads will be able to take up the CPU, execute yield () thread is likely to be executed immediately after entering the suspended state.

 

What degree of concurrency is 35.Java in ConcurrentHashMap

ConcurrentHashMap the actual map is divided into several parts to achieve its scalability and security thread. This division is obtained by using the degree of concurrency, which is an optional parameter ConcurrentHashMap class constructor, the default value is 16, so that multiple threads can avoid contention.

 

What is 36.Java in Semaphore

A new synchronization classes under JUC, which is a count signal. Conceptually, Semaphore semaphore maintains a set of permissions. If necessary, block the permit is available each acquire (), and then get the license. Each release () adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects, Semaphore only the number of available licenses is counted, and act accordingly. Semaphores are often used multi-threaded code, such as a database connection pool.

 

37. If you submit the task, the thread pool queue is full. What hair would give birth?

This question was very cunning, many programmers will think the task will be blocked until the thread pool queue has vacancy. In fact, if a task can not be scheduled for execution so ThreadPoolExecutor's submit () method will throw a RejectedExecutionException exception.

 

38.Java thread pool submit () and execute () method What is the difference

Both methods can be submitted to the thread pool task, return type execute () method is void, it is defined in the Executor interface, and submit () method returns an object held by Future calculation results, which is defined in ExecutorService interface, it extends the Executor interface, like the other thread pool ThreadPoolExecutor and ScheduledThreadPoolExecutor have these methods.

 

39. What is the blocking method?

Blocking method means that the program will wait until the process is completed do not do other things during, ServerSocket's accept () method that has been waiting for client connections. Here is the obstruction before the call returns, the current thread is suspended, it will not return until after the results. In addition, asynchronous and non-blocking method returns before the task is completed.

 

40.Swing is thread safe?

You can be sure of the answer given, Swing is not thread safe. You can not by any thread to update Swing components, such as JTable, JList or JPanel, In fact, they can only be updated by GUI or AWT thread. This is why Swing provides invokeAndWait () and invokeLater () method to get the GUI update requests from other threads. These methods update request into the AWT thread queue, may wait, the result may be returned directly via asynchronous update.

 

41.Java in invokeAndWait and invokeLater What is the difference

These two methods are Java Swing API available to developers for dispatching thread updated with GUI components from the current thread instead of the event. InvokeAndWait () synchronization update GUI components, such as a progress bar, once progress updates, the progress bar should make the appropriate change. If the progress is tracked by multiple threads, then call invokeAndWait () method to request event-dispatching thread components updated accordingly. The invokeLater () method is called asynchronously updated component.

 

Those 42.Swing API method is thread safe?

While Swing is not thread safe, but there are some methods that can be multi-thread safe call. The repaint (), revalidate (). JTextComponent the setText () method and the JTextArea insert () and append () method is thread-safe.

 

43. How to create Immutable objects in Java

Immutable objects can be shared without synchronization, reduce synchronization overhead when the object concurrent access. But Java does not @Immutable this comment character, to create immutable class, to implement the following steps: Initialize all members via the constructor, do not provide for a variable setter methods, all members declared private, so it does not allow direct access to these members, the getter method, do not directly return the object itself, but the cloned object and returns a copy of the object.

 

What is 44.Java ReadWriteLock that?

In general, read-write lock is used to improve the outcome of the performance of concurrent programs locking separation techniques. Java, Java 5 ReadWriteLock is in a new interface, a maintenance ReadWriteLock lock one pair of associated, one for read-only operations and one for writing. In the absence of a read-write thread lock may read simultaneously by multiple threads to hold. Write locks are exclusive, you can use the JDK ReentrantReadWriteLock to implement this rule, which supports up to 65,535 write locks and read locks 65535.

 

What are you doing loop 45. The multiple threads are?

Busy cycle is the cycle so that a programmer with thread to wait, unlike traditional methods wait (), sleep () or yield () they have given up control of the CPU, and CPU busy cycle will not give up, it is running an empty cycle. The goal is to retain the CPU cache, when the multi-core system, a waiting thread might wake up in another kernel is running, it will rebuild the cache. In order to avoid and reduce the waiting time to rebuild cache rebuild you can use it.

 

46.volatile variables and atomic variables What is the difference

volatile variables and atomic variables look like, but the functionality is not the same. volatile variables can ensure that first relationship, that is, the write operation will occur before a subsequent read operation, but it does not guarantee atomicity. For example volatile modified count variable count ++ so operations are not atomic. Class provides the atomic AtomicInteger method may allow such operations are atomic as getAndIncrement () method will be atomic increment of the current value plus one, reference variables and other data types may be carried out similar operations.

 

47. If the thread in sync blocks thrown what will happen?

Whether you sync block is normal or abnormal exit, which thread will release the lock, so the contrast lock interfaces I prefer sync block, because it I do not have to spend energy to release the lock, this feature can release the lock achieved in the finally block inside.

 

48. How to create a thread safe in Java Singleton

Five kinds, acute loading, synchronization method, a double lock object, the internal static class, enum

 

49. How do I force starts a thread?

This problem is like how to force Java garbage collection, there is no method that, to carry out garbage collection, although you can use the System.gc (), but does not guarantee success. In Java there is no way forced to start a thread, it is the thread scheduler controls and Java did not disclose the relevant API.

 

What fork join framework 50.Java that?

fork join framework is a highly efficient tool that appears JDK7, Java developers can use it to take full advantage of multiple processors on modern servers. It is designed for those who can recursively sub-divided into a number of modular design, the aim of all the available processing power to improve the performance. fork join the framework of a huge advantage is that it uses a work-stealing algorithm, can do more worker threads can perform tasks to steal from another thread.

 

51.Java multiple threads call wait () and sleep () method What is the difference?

Java programs wait and sleep will cause some form of suspension, they meet different needs. wait () method implies condition wait, wait if the condition is true and the other thread wakes up when it releases the lock, and sleep () method is only freeing the CPU to the current thread or make a short pause, but will not release the lock.

 

52. Models for parents delegate

findLoadedClass(),LoadClass(),findBootstrapClassOrNull(),findClass(),resolveClass()

 

53.NIO, AIO, BIO

BIO synchronous blocking the IO i.e., suitable for a smaller number of connecting and fixing the structure, this embodiment of server resources requirements are relatively high, limited concurrent applications, the only choice for the JDK1.4 before, but the program intuitive, simple, easy to understand.

NIO that is synchronous non-blocking IO, applies to more than the number of connections and the relatively short connection architecture, such as chat server, concurrent limited to the application, the program is more complex, JDK1.4 began to support.

AIO Asynchronous non-blocking IO, applies to more than the number of connections and the connection long architectures, such as photo albums server, call the OS to fully participate in concurrent operation, programming is more complex, JDK1.7 began to support

 

Published 400 original articles · won praise 940 · views 490 000 +

Guess you like

Origin blog.csdn.net/A_BlackMoon/article/details/102828096