Core Java Fundamentals Summary

Source: Internet
Author: User
Tags thread class

What's the difference between collection and collections?

Collection is an interface collection that provides a set of common interface methods for manipulating collection objects, designed to provide a uniform interface method for a variety of collections.

Collections is a wrapper class for a collection class that provides a set of static methods and operations such as indexing, sorting, threading, and so on, while most methods are used to process linear tables. Collections cannot be instantiated, it is like a tool class that serves the collection framework, and when a method in the collection class is called, if the corresponding collection object is null, it is thrown nullponiterexception .

What is a thread? What is the process? What are their differences and connections?

A thread is a unit of execution that can execute a program code during the execution of a program, and in the Java language, the state of a thread is: run, ready, hang, end.

A process is a program that is being executed, a thread is sometimes called a lightweight process, a process usually has multiple threads, and each thread will share the program's memory Space (code snippets, data segments, heap space) and process-level resources (such as open files), but each thread has its own stack space.

At the operating system level, the process is the basic unit of the program's operation, and in a process there are often multiple threads that do not interfere with each other concurrently. So why use multithreading?

The advantages of using multithreading are:

1. Using multithreading can reduce the response time of the program.

2. Creating a thread is less expensive than a process.

3. Multi-CPU and multi-core can run multiple threads.

4. The use of multithreading can simplify the program, easy to understand and maintain the program, can transform complex problems into simple multithreading to execute.

What is synchronization? What is async?

In a multithreaded environment, you often encounter resource sharing issues. That is, when multiple threads invoke the same resource, they are in some order to ensure that only one thread invokes the resource per session, otherwise unpredictable results will occur. In this case, the data must be synchronized, such as multiple threads simultaneously write to the same data, thread A needs to use a resource, and this resource is being used by B, only when thread B ends the use of resources, thread A can use the resource, the synchronization mechanism can guarantee the security of resources.

To achieve synchronization, you must obtain the lock of the object, which ensures that only one thread enters the critical section (the code block that accesses the mutex) at each time, and that the other thread cannot enter the critical section until the lock is released, and if there are other threads that want to obtain the lock on the object, they can only enter the waiting queue. Only when the thread that owns the lock of the object exits the critical section, the lock in the waiting area runs at the highest level to enter the critical section, using the shared code.

Java provides language-level support for the synchronization mechanism, which can be synchronized by invoking the Sychronized keyword directly, but synchronization is not a "balm". It is at the expense of a lot of overhead, and using synchronization can sometimes cause deadlocks. So synchronization control is not the more the better, should avoid unnecessary use of synchronization. There are two ways to implement synchronization: one is to implement synchronization through code blocks, and the other is to implement synchronization by invoking a method.

Asynchronous is similar to non-blocking, because each thread contains data or methods required by the runtime, so when you do input and output processing, you do not need to care about the behavior and state of other threads, and you do not need to wait for the input and output to be processed and return if the program calls a very time-consuming method on the object. And there is no need to wait for the return, which is the need for asynchronous programming, asynchronous can improve the efficiency of the program.

For example in life, synchronization is I call you to eat, you immediately and I go to dinner, and asynchronous is I call you to eat, you can eat together first, you can eat later, you can not eat.

How do I implement multithreading?

Java Virtual machine allows the program to run multiple threads concurrently, then how to implement multithreading, there are the following 3 ways:

1. Inherit the thread class, overriding the run () method.

The thread class is essentially an instance of runnable, which is an instance of the thread, and the only way to open the thread is to call the start () method of the thread class, which is a native (local) method, It will start a new thread and execute the Run () method (the thread class's Run method is an empty method), which can be created by customizing the thread class directly extend and overriding the Run method to create a new thread and use the custom Run method, note that The open thread is not a direct execution of multithreaded code, but the multithreading is set to run too, specifically when to turn on multithreading with operating system control.

2. Implement the Runnable interface and implement the run () method of the interface.

(1) Customizing the class and implementing the Runnable interface to implement the run () method of the interface

(2) Create an object thread, instantiate the thread as a parameter with the object implementing runnable

(3) Call the Start () method of the thread.

In fact, whether through multithreading or implementation of the Runnable interface, it is called the thread API to handle multithreading.

3. Implement the callable interface and override the call () method.

The callable interface is a functional class of the Execute framework, and its functions are similar to runnable, but more powerful than runnanble, mainly in the following three points:

(1) Callabble there will be a return value at the end of the task, and Runnable does not.

(2) The call method in callable can throw an exception, and the Run () method in runnable cannot throw an exception.

(3) Using callable will produce a future object, which is the result of an asynchronous calculation, which provides a way to check whether the calculation is complete, the thread belongs to the asynchronous computational model, so it cannot get the return value of the function from other threads, in which case You can use the future to monitor the scenario in which the target thread invokes the call method, and when the Get () method in the future is called, the thread is blocked until the call ends and the result is returned.

Of the above 3 methods, the first two do not have a return value, only the last one with the return value. When multi-threading is required, it is recommended to implement the Runnable interface, mainly because: first, the thread class provides many ways for a derived class to invoke or override, and only the run () method must be overridden to implement the main functionality of the thread in the Run method. This is, of course, a necessary way to implement the Runnabel interface, and secondly, many Java developers assume that inheritance occurs only when they are strengthened or modified, so the thread and the effect of implementing the Runnnable interface are the same. In this case, it is best to implement multithreading by implementing the Runnanble interface.

What are the implementation methods of multithreading synchronization?

When using multithreading to access the same resource, it is very prone to thread-safe problems (for example, when multiple threads modify a thread at the same time, some thread changes to the data is lost), in which case the data need to be synchronized, in the Java language, provides 3 ways to implement multi-threaded synchronization.

<1>synchronized keywords

In the Java language, each object has an object lock associated with it, which indicates that the object can only be owned by one thread at any time, and when a thread needs to call a section of synchronized code, it needs to get the lock on the snippet to continue execution, releasing the lock after execution is complete.

In the Java language, the Sychronized keyword has two main uses (the Synchronized method and the synchronized block), can also be used to decorate static methods and instances, etc., but it will affect the efficiency of the operation of the program.

(1) Add the Synchronized keyword before the method declaration, with the following example:

Public synchronized void Mutithreadaccess ()

In the above method, put the resources that need to be shared into mutithreadaccess (), can ensure that the method at the same time R can only be accessed by one thread, so as to ensure the security of multi-threaded access. However, when the method body of a method is very large, the use of the Synchronized method can greatly affect efficiency, and in order to solve this problem, Java provides a synchroonized block.

(2) Synchronized block, synchronized can either set any piece of code to synchronized, you can also specify the object lock, there is very high flexibility. The code examples are as follows:

Synchronized (SyncObject) {

Accessing the SyncObject code

}

2.wait () and Notify () method.

When you use synchronized to decorate a shared resource, if one thread A1 executes one synchronized code and the other thread executes the same segment sychronized code for the same object, the thread A2 waits until the thread A1 execution completes before it can continue execution. You can then call the object's Wait () method and the Notify () method.

During the execution of the synchronized code, the thread can call the object's Wait () method, release the object lock, enter the wait state, and call the object's notify () method or the Notifyall () method to notify the thread to get the object lock. The Notify () method wakes only one thread (waiting for the first in the queue), and allows the object lock to be obtained, and the Notifyall () method wakes up all threads to allow them to acquire the lock (not guaranteeing that all threads get locks and let them compete).

<2>lock () method.

JDK5 provides a lock interface and its implementation class Reentrantlock (re-entry Lock), and lock can also be used to implement multi-threaded synchronization, in particular, mainly through the following methods to achieve:

(1) lock (), by blocking the thread to achieve synchronization, if acquired to the lock, will immediately return, if the lock is owned by another thread, will wait, know to get to the lock.

(2) Trylock (). Just try to get the lock. Returns true if the lock is obtained, false if no lock is obtained.

(3) Trylock (long timeout,timeunit unit). Returns False if a lock is acquired, returns immediately if no lock is obtained, waits until the parameter specifies the time unit, and returns True if the lock is acquired during the wait process.

(4) lockinterruptibly (), if the lock is acquired, returns immediately, if the lock is not acquired, the current thread is dormant until the lock is acquired, or when the thread is interrupted by other threads. The biggest difference between it and the lock method is that if the lock () method gets no locks, it will always be in a blocking state and the interrupt method will be ignored.

What is the difference between sleep () and the Wait () method?

Sleep () is a program used to suspend a thread execution, and wait () is also a program used to suspend a thread, for example, when a thread interacts with a wait () call request to a synchronization object x, the thread pauses execution.

Specifically: the difference between the sleep () and wait () methods is mainly expressed in a few ways:

1. The principle is different, the sleep () method is a static method of the thread class, is the thread to control its own process, he will cause the thread to suspend execution for a period of time, and the execution opportunity to other threads, wait until the time elapsed, this thread will automatically wake up. For example, when a thread performs a chime function and prints a time every second, you need to add a sleep () method before the printing method so that you can execute it every 1s, as if it were an alarm clock. The wait () method is the object () method, which is used for communication between threads, which causes the process that currently owns the lock to wait until the other thread calls the Notify () method (or the Notifyall method) to "Wake up". But developers can also give it a time to wake up automatically, with the Wait () method and notify and Notifyall ().

2. The mechanism for locking is different, because the sleep () method's primary role is to let the thread suspend execution for a period of time, the time is automatically recovered, does not involve the communication between the threads, so calling the sleep () method does not release the lock. This allows other synchronized data in the object where the thread resides to be used by other threads. For example: For example, Xiao Ming take the remote control period, you can use their own sleep method every 10min tune a channel, and in this 10min, the remote control is still in his hand.

3. The use of regions differs, because the wait () method is special, so it must be placed in a synchronous control method or a synchronous statement block, and the sleep () method can be used anywhere.

The sleep () method must catch the exception, and wait (), notify (), and Notifyall () do not need to catch the exception, and during sleep it is possible for the other object to call its interrupt (), Generates a Interruptedexception exception.

Because sleep does not release the "Lock Flag", it is easy to cause a deadlock problem, so in general, the Sleep method is not recommended and the wait () method is recommended.

How do I end a thread?

In the Java language, you can end a thread by calling the Stop () method or the Suspend () method. When a thread is terminated with thread.stop (), all monitoring resources of the thread are stopped, and objects monitored by those monitoring resources are found to be "inconsistent" by other threads, causing the output to be not necessarily the original setting. If you use the Suspend () method to stop a thread, a deadlock can occur (a deadlock is two or more than two threads that cause each other to wait in the resource race, and two threads cannot execute if there is no outside help). Because you do not need to release locks when using suspend, this can cause a problem: If you call suspend () to suspend a thread with a lock, only the lock recovery is released. If you call suspend (), the other thread wants to get the same lock, which causes a deadlock. So both of these unsafe methods of terminating threads are not recommended.

So, how do you terminate a thread? It is recommended that the thread end itself into the dead state, that is, the thread finishes running the run () method, that is, a way for the thread to end the run () method. Specifically, you can add a flag flag to the thread to control whether the loop executes, leaving the threads out of the run () method's execution end thread. Examples are as follows

public class Thread implement () {

public static void Main String (args[]) {

public void stop{

Flag=false;

}

public void Run () {

while (flag);

DoSomething

}

}

}

In the above example, the Stop method that calls thread is able to terminate the thread, but there is also a problem, the method described above is not available when the thread is in a non-running state (when the sleep () method is called or when the Wait () method is called or the I/O is blocked).

The interrupt () method can be used to break the blocking situation, and when the Interruot () method is called, a interruptexception () exception is thrown and the thread is safely exited by capturing the exception in run ().

What is the difference between synchronized () and lock ()?

Java provides two locking mechanisms to achieve synchronization of resources, synchronized () and lock (), where synchronized () uses the Thing object's Wait (); notify (); Notifyall (), Lock () is a codition to perform the synchronized () implementation of the function of the thread scheduling.

Specifically, synchronized () and lock () differ mainly in the following points:

(1) different usage. Adding synchronized,synchronized to the object that needs to be synchronized can also be placed in a method, a block of code, where the locked object is enclosed in parentheses, and lock () must display the specified starting and ending positions. Synchronized is managed by the JVM virtual machine to execute, and lock () is implemented through code, and lock () has a clearer line semantics than synchronized.

(2) different performance. An implementation of the lock interface is added to the Jdk5 Reetrantlock (), which not only has the same concurrency and memory semantics as synchronized, but also many lock polls, waits, timed locks, interrupt locks, and so on. In terms of functionality: When resources are competitive, the performance of synchronized is similar to lock (), and when resources are competitive, the performance of synchronized falls sharply, while the performance of lock remains essentially the same.

(3) The locking mechanism is different. Synchronized () acquires lock and release lock are in block structure, when acquiring multiple locks, must be released in reverse order, and is automatically released, not because of an exception without releasing the lock to cause a deadlock, and lock requires the developer to manually release, must be released in final, otherwise it will cause a deadlock. At the same time, lock () has a more powerful function than synchronized (), and its Trylock () method can acquire locks in a non-blocking manner.

Although both synchronized and lock can achieve multi-threaded synchronization, it is best not to use both locks at the same time, because the mechanisms of the two locks are different, they are run independently, can be seen as two different locks, at run time, but the results may be different.

What is a daemon thread?

Java provides two kinds of threads: the daemon thread and the user thread, the daemon thread is also called "service Process", "Sprite Thread", "background thread", refers to the thread that provides the usual service in the background when the program runs, it is not an indispensable part of the program, in layman's name, it is the "nanny" of all non-daemon threads

The user thread and the daemon thread are almost the same, the only difference is that as long as a user thread is not finished, the program cannot end, all the non-daemon threads end, the program ends, the JVM ends, because the thread that needs to be guarded is gone, the daemon thread is not working, so the program ends and the program "Kill" the daemon thread. In layman's terms, the program will not end as long as a non-daemon thread exists in the program.

In the Java language, the daemon thread generally has a lower priority, it is not provided only by the JVM, and the user sets the daemon itself when writing the program, by invoking the Setdaemon (ture) method of the object before start (), if the argument is set to False, Represents the set to user process mode. It is important to note that if another thread is created in one daemon, the new thread defaults to the daemon thread, and so is the user thread.

How does the Join method work?

In the Java language, the Join method is used to enable the thread that invokes the method to execute the join () method after the run () method is executed. In simple terms, it is the merging of two threads, which is used to implement synchronization functions. Specifically, thread A calls thread A's join method to wait for the end of thread A. For example, thread A calls thread A's join (2000) to wait for thread A to end, waiting for only 2s.


This article from the "Java Learning direction" blog, declined reprint!

Core Java Fundamentals Summary

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.