Threads and exceptions

Source: Internet
Author: User
Tags finally block instance method thread class throwable try catch volatile

Threads Thread

There are two ways of implementing Multithreading:

1, inherit the thread class (nature is also an example of implementing the Runnable interface)

Thread class source code

 Public class Thread implements Runnable {}

Define a thread

Public class mythreadextends thread{    publicvoid run () {     // Override the Run method      New MyThread (); Thread1.start ();

The only way to start a thread is through the start () instance method of the thread class. The start () method is a native method that starts a new thread and executes the run () method.

2. Implement Runnable interface

If a class already extends another class, it cannot directly extends the Thread, at which point a runnable interface must be implemented

 Public class extends Implements runnable{    publicvoid run () {     // override Run Method     }} 

To start a thread, you first instantiate a thread and pass in your own thread instance

MyThread MyThread = new MyThread ();

Thread thread = new Thread (mythread);

Thread.Start ();

difference

Inheriting the thread class to implement multi-threading is equivalent to taking out three things and handing them over to three threads respectively. Because Mythread inherits thread, three threads were created at the time of new Mythread when three objects were created.

Implementing runnable is equivalent to taking one thing for three threads to do, and new MyThread is equivalent to creating a task and then instantiating three thread. Multi-threaded instance variables are also shared, so the implementation of the Runnable interface is suitable for resource sharing.

parsing

(1) Start () method

starting a thread with the Start method is a real implementation of multi-threading, starting a thread by invoking the start () method of the thread class, at which point the thread is in a ready (operational) state and is not running, and once the CPU time slice is taken, the run () starts Method (The Run () method is the point at which the execution begins). Note, however, that you do not have to wait for the run () method to complete before you can proceed with the following code. So the run () method does not implement multithreading.

(2) Run () method

The run () method is just a common method of the class, if you call the Run method directly, the program is still only the main thread, the program execution path is only one, or to execute sequentially, or to wait until the Run method body execution is completed before you can continue to execute the following code.

(3) The thread can set the priority size: thread1.setpriority ();

(4) The thread class is defined in the Java.lang package. A class can implement multithreaded operations by inheriting the thread class while overriding the Run method in this class, but a class can inherit only one parent class.

The runnable interface avoids the limitations of inheritance, and a class can inherit multiple interfaces. The share that applies to the resource.

(5) threads, runnable, and callable are implemented in the same way.

(6) The Wait () method must be caught by a try catch exception, and the thread-throwing error is generally related to interruptedexception.

(7) Set a thread to daemon (background thread), which means that the main thread ends and the background threads end automatically.

(8) There are three ways to stop a thread : ① calls the Stop () method ② thread execution completes ③ exception throws.

Daemon Threads ( Daemonthread )

A daemon thread, also known as a "service process", "background thread", is a thread that provides a common service in the background while the program is running. If the user thread is all out of operation, only the daemon thread is present, and the JVM exits.

The daemon thread generally has a lower priority, and the user can set the daemon thread himself, calling the Setdaemon (true) method of the object before invoking the start () method , and setting it to false to indicate the user process pattern. When another thread is created in one of the daemons, the new threads are still daemon threads.

The typical example is the garbage collector.

Thread Synchronization

(1) Synchronization method

Use the Synchronized keyword to modify the method. Because each object in Java has a built-in lock, the built-in lock protects the entire method when the method is decorated with this keyword. You need to get the built-in lock before calling the method, otherwise it will be in a blocking state.

(2) Synchronizing code blocks

The statement block, which is decorated with the Synchronized keyword, is automatically added with the built-in lock for synchronization.

Synchronization is a high-overhead operation, so you should minimize the content of synchronization.

(3) Wait and notify

Wait (): Causes the thread to process the wait state, and releases the lock of the object held.

(4) Using special variables (volatile) for thread synchronization

(5) thread synchronization with a re-entry lock

(6) Using local variables for thread synchronization

(7) thread synchronization with blocking queues

volatile and synchronized

  volatile is used primarily when multiple thread-aware instance variables are changed, allowing each thread to get the most recent value. It enforces the visibility of the data by forcing threads to refer to variables from main memory each time, rather than reading variables from the thread's private memory.

Compare :

①volatile is lightweight and can only modify variables. Synchronized is heavyweight and can be modified.

②volatile can only guarantee the visibility of the data and cannot be used for synchronization because multiple threads concurrently accessing volatile modified variables are not blocked.

Synchronized not only guarantees visibility, but also guarantees atomicity, because only the thread that obtains the lock can enter the critical section, guaranteeing that all statements in the critical section are executed. Blocking occurs when multiple threads scramble for synchronized lock objects.

Thread Safety

Thread safety consists of two aspects:① visibility; ② atomicity.

From the example above, it can be seen that using volatile alone does not guarantee thread safety. Synchronized, however, can implement thread security.

state transitions between threads

Thread from new to the end of the general there are 5 states, for new, can run, run, block, end, where blocking is not required state!

1. NEW: A new Thread object has been created.

2. Operational (runnable): After the thread object is created, other threads (such as the main thread) call the object's start () method. The thread in this state is in a pool of running threads, waiting for the thread to be dispatched to get the CPU right.

3. Run (running): The Running State (runnable) thread obtains the CPU time slice (TimeSlice) and executes the program code.

4. Block: Blocking state refers to a thread that has given up the CPU for some reason, or let the CPU TimeSlice, temporarily stop running. Until the thread enters the operational (runnable) state, there is a chance to get the CPU TimeSlice again to the run (running) state. There are three types of blocking:

(i). Wait for blocking: the thread that is running (running) executes the o.wait () method, and the JVM puts the thread into the waiting queue (the waitting queues).

(b). Synchronous blocking: When a thread running (running) acquires a synchronization lock on an object, if the synchronization lock is occupied by another thread, the JVM puts the thread into the lock pool.

(iii). Other blocking: The thread that runs (running) executes the thread.sleep (long ms) or T.join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state time-out, join () waits for the thread to terminate or times out, or the I/O process is complete, the thread is re-transferred to the operational (runnable) state.

5. Death (dead): The thread Run (), main () method execution ends, or the run () method is exited due to an exception, the thread ends the life cycle. The thread of death cannot be resurrected again.

sleep () and wait ()

sleep () is a thread-class method that causes this thread to pause execution for a specified time, giving the execution opportunity to other threads, but the monitoring state remains and is automatically restored when it is time. Calling sleep does not release the object lock.

Wait () is the method of the object class that calls the wait method on this object to cause the thread to discard the object lock, to wait for the lock pool to wait for the object, and only after the Notify method (or Notifyall) is issued for this object to enter the object lock pool preparation gets the object lock into the ready state .

Difference:

Sleep must catch exceptions, while wait,notify and notifyall do not need to catch exceptions.

  The sleep method does not release the lock, and the wait method frees the lock so that other threads can use the synchronization control block or method.

Condition is only present in Java 1.5, which is used instead of the traditional object's Wait (), notify () to achieve collaboration between threads, compared to wait (), notify () with object, Using Condition1 's await (), signal () is a way to make collaboration between threads more secure and efficient. Therefore, it is generally recommended to use condition, the blocking queue actually uses condition to simulate inter-threading collaboration.

Condition is an interface, the basic method is the await () and the signal () method;

dead Lock

Causes and necessary conditions for deadlock generation

The main causes of deadlocks are:

(1) Due to insufficient system resources.

(2) The sequence of progress of the process is not appropriate.

(3) Improper allocation of resources and so on.

If the system has sufficient resources, the resource requests of the process can be met, the likelihood of deadlocks is very low, otherwise it will be locked into a deadlock because of the contention for limited resources. Second, the process is run in a different order and speed, and may also produce a deadlock.

The four necessary conditions for creating a deadlock:

(1) Mutex condition: A resource can only be used by one process at a time.

(2) request and hold condition: When a process is blocked by a request for resources, it remains in place for the resources that have been obtained.

(3) Conditions of deprivation : The resources that the process has acquired cannot be forcibly deprived of until the end of its use.

(4) cyclic waiting condition: a cyclic waiting resource relationship is formed between several processes.

These four conditions are necessary for the deadlock, as long as the system has a deadlock, these conditions must be established, and as long as one of the above conditions is not satisfied, there will be no deadlock.

process, thread, fiber

A process is usually defined as an instance of a running program, a program with a certain set of independent functions on a data collection, in turn, is a system for resource allocation and scheduling of an independent unit.

A thread is an entity of a process that is the basic unit of CPU dispatch and dispatch, which is a smaller unit that can run independently than a process. The thread does not own the system resources at all, it has only a few resources (such as program counters, a set of registers and stacks) that are essential in the run, but it can share all the resources owned by the process with other threads that belong to one process.

fibers are implemented in user-mode code, and the kernel does not know about fiber, and they are dispatched according to user-defined algorithms. Because of the definition of fiber scheduling algorithm, in the kernel, the fiber adopts non-preemptive scheduling method.

(1) Relationship

One thread can create and revoke another thread, and can execute concurrently between multiple threads in the same process. Relative to a process, a thread is a concept that is closer to the execution body, it can share data with other threads in the process, but has its own stack space and has a separate execution sequence.

(2) Difference

The main difference between processes and threads is that they are different ways to manage operating system resources.

The process has a separate address space, and after a process crashes, it does not affect other processes in protected mode, and the thread is just a different execution path in a process.

Thread has its own stack and local variables, but there is no separate address space between the threads, a thread dead is equal to the entire process dead, so the multi-process program is more robust than multithreaded programs, but in the process of switching, the cost of large resources, efficiency is worse. But for some concurrent operations that require simultaneous and shared variables, only threads can be used, and processes cannot be used.

A. A program has at least one process, and a process has at least one thread.

B. Thread size is smaller than the process, which makes the multi-thread procedure high concurrency.

C. The process has an independent memory unit during execution, and multiple threads share memory, which greatly improves the efficiency of the program's operation.

D. Threads are still different from the process in the execution process. Each separate thread has a program run entry, sequence of sequence execution, and exit of the program. However, threads cannot be executed independently, and must be dependent on the application, which provides multiple threads of execution control.

E. From a logical point of view, the meaning of multithreading is that in an application, multiple execution parts can be executed concurrently. However, the operating system does not consider multiple threads as separate applications to implement scheduling and management of processes and resource allocation. This is the important difference between processes and threads.

thread safety and thread insecurity

Thread Safety is a multi-threaded access, the use of locking mechanism, when a thread access to one of the class's data, protection, other threads can not access until the thread is finished reading, the other threads are available, no data inconsistency or data pollution. Vector, HashTable, StringBuffer

thread Insecurity is not providing access protection for data, it is possible that multiple threads have changed data sequentially resulting in data being dirty data.

Thread safety is caused by global variables and static variables, if the global variables in each thread, static variables only read operations, and no write operations, in general, this global variable is thread-safe, if more than one thread to write at the same time, it is generally necessary to consider thread synchronization, otherwise it may affect thread safety.

Example: Turn on 1000 threads to add elements to ArrayList, add 100 elements to each object, and eventually size should be 100000, and the result will find that size is less than 100000

Exception

  exception Inheritance Structure : The base class inherits exception such as Throwable,error and exception inheritance throwable,runtimeexception and IOException.

Non-runtimeexception is generally an external error (not an error), which must be captured by the Try{}catch statement block

Creating an exception manually requires writing new Exception

running exceptions can be handled by the Java Virtual machine itself. non-running exceptions , we should catch or throw.

Throw   keyword for throwing exceptions

throws   The keyword can declare the exception that the method throws on the method, and then throws the exception object through a throw inside the method.

Runtime Exceptions: All are runtimeexception classes and their subclass exceptions, such as NullPointerException, indexoutofboundsexception, etc., these exceptions are not checked exceptions, the program can choose to capture the processing, or can not be processed, is usually caused by a logical error.

Non-runtime exception: is an exception other than RuntimeException, and the type belongs to the exception class and its subclasses. The exception must be handled, not handled, and the program cannot be compiled through.

finally

In both cases, the finally statement is not executed:

(1) The Try statement is not executed, as returned before the try statement, so that the finally statement does not execute, which also shows that the finally statement is executed by the necessary rather than sufficient condition is: the corresponding try statement must be executed to.

(2) There is system.exit (0) in the try block, such a statement, System.exit (0), terminates the Java Virtual Machine JVM, even the JVM is stopped, all is finished, and the finally statement is not executed.

1. The finally statement is executed after the return statement of the try is executed.

2. The return statement in the finally block overrides return in the try block .

3, if no return statement in the finally statement overrides the return value, then the original return value may be changed by the change in the finally and may not be changed.

4. The finally statement executes before the return and throw statements.

Summary :

The statement of a finally block is returned before the return statement in a try or catch is executed and the modified statement in the finally may or may not affect the return value that has been determined in the try or catch. If there is a return statement in Finally, the return statement in the try or catch is overwritten directly.

Threads and exceptions

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.